Skip to content

armgit / soju

Public Imported from GitHub
0

Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.

Play counts say how each start went and include games started from Steam's window; Steam's redistributables are not a game; 1.14.32 (#158)

Mikek8724facd3f0b
diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml
index e2ceb3e8742..2c253b99c52 100644
--- a/.github/workflows/check.yml
+++ b/.github/workflows/check.yml
@@ -16,6 +16,7 @@ jobs:
for script in scripts/*.sh scripts/soju; do bash -n "$script"; done
python3 -m unittest discover -s tests -q
node --test tests/test_steam_login.cjs
+ node --test tests/test_stats_worker.mjs
- name: Released files still resolve, Homebrew installs the newest release
env:
GITHUB_TOKEN: ${{ github.token }}
diff --git a/README.ko.md b/README.ko.md
index c6ebfa57b3d..800a88a7f22 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -8,7 +8,7 @@ Soju는 M1 이후 맥에 **Battle.net·Steam·Epic Games·GOG GALAXY·EA 앱·Ro
![Soju 통합 게임 라이브러리](docs/assets/soju-library.png)
-**[Soju 1.14.31 맥 앱 받기](https://github.com/BCD1210/soju/releases/download/v1.14.31/Soju-1.14.31-macos-arm64.zip)**, 또는 터미널에서 설치:
+**[Soju 1.14.32 맥 앱 받기](https://github.com/BCD1210/soju/releases/download/v1.14.32/Soju-1.14.32-macos-arm64.zip)**, 또는 터미널에서 설치:
```bash
brew install BCD1210/soju/soju
@@ -83,7 +83,7 @@ soju install # 이후: soju battlenet / soju d2r / soju steam / soju epic /
설치기는 **다운로드 전에 원하는 런처부터 선택**합니다. Steam만 선택하면 CX 엔진과 애플 GPTK를 받지 않습니다. Steam 그래픽 구성요소는 SHA-256으로 검증한 뒤 Soju 전용 Wine 11.0 환경에 자동으로 설치합니다. Battle.net·Epic·GOG는 공통 CX 엔진과 사용자가 별도로 받은 애플 GPTK를 사용합니다. 각 런처의 보틀·로그인·게임은 독립적으로 유지합니다.
-[Soju 맥 앱 다운로드](https://github.com/BCD1210/soju/releases/download/v1.14.31/Soju-1.14.31-macos-arm64.zip): 네이티브 앱 프리뷰에서 설치된 게임과 보유 게임, 스토어 검색, 즐겨찾기, 게임 실행, 플랫폼 관리를 한 화면에서 다룰 수 있습니다. [설치 안내와 요구 사항](docs/DESKTOP.md)을 확인해 주세요.
+[Soju 맥 앱 다운로드](https://github.com/BCD1210/soju/releases/download/v1.14.32/Soju-1.14.32-macos-arm64.zip): 네이티브 앱 프리뷰에서 설치된 게임과 보유 게임, 스토어 검색, 즐겨찾기, 게임 실행, 플랫폼 관리를 한 화면에서 다룰 수 있습니다. [설치 안내와 요구 사항](docs/DESKTOP.md)을 확인해 주세요.
## 일상 명령
diff --git a/README.md b/README.md
index 7a034c2df6a..3a0d76c6c82 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@ Soju installs the official Windows launchers for **Battle.net, Steam, Epic Games
![Soju unified game library](docs/assets/soju-library.png)
-**[Download Soju 1.14.31 for Mac](https://github.com/BCD1210/soju/releases/download/v1.14.31/Soju-1.14.31-macos-arm64.zip)**, or install from the terminal:
+**[Download Soju 1.14.32 for Mac](https://github.com/BCD1210/soju/releases/download/v1.14.32/Soju-1.14.32-macos-arm64.zip)**, or install from the terminal:
```bash
brew install BCD1210/soju/soju
@@ -85,7 +85,7 @@ soju install # then: soju battlenet / soju d2r / soju steam / soju epic / so
The installer asks which launchers you want **before downloading anything**. Steam-only installs skip the CX engine and Apple GPTK. Steam rendering components are downloaded with SHA-256 verification and installed in a Soju-owned Wine 11.0 runtime. Battle.net, Epic and GOG use the shared CX engine and your separately downloaded Apple GPTK. Each official client keeps its own bottle and shortcut in `~/Applications`.
-[Download Soju for Mac](https://github.com/BCD1210/soju/releases/download/v1.14.31/Soju-1.14.31-macos-arm64.zip): the native desktop preview includes installed and owned games, store search, favorites, game launching and platform management. See [desktop setup and requirements](docs/DESKTOP.md).
+[Download Soju for Mac](https://github.com/BCD1210/soju/releases/download/v1.14.32/Soju-1.14.32-macos-arm64.zip): the native desktop preview includes installed and owned games, store search, favorites, game launching and platform management. See [desktop setup and requirements](docs/DESKTOP.md).
## Everyday commands
diff --git a/README.zh.md b/README.zh.md
index e5bbcaf78dc..5eb186e1a97 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -8,7 +8,7 @@ Soju 在 M1 及更新的 Mac 上安装 **Battle.net、Steam、Epic Games、GOG G
![Soju 统一游戏库](docs/assets/soju-library.png)
-**[下载 Soju 1.14.31(Mac)](https://github.com/BCD1210/soju/releases/download/v1.14.31/Soju-1.14.31-macos-arm64.zip)**,或在终端安装:
+**[下载 Soju 1.14.32(Mac)](https://github.com/BCD1210/soju/releases/download/v1.14.32/Soju-1.14.32-macos-arm64.zip)**,或在终端安装:
```bash
brew install BCD1210/soju/soju
@@ -83,7 +83,7 @@ soju install # 然后:soju battlenet / soju d2r / soju steam / soju epic /
安装器会**先询问要安装哪些启动器,再下载对应组件**。仅选择 Steam 时,不会下载 CX 引擎或 Apple GPTK。Steam 图形组件经过 SHA-256 校验后,自动安装到 Soju 专用的 Wine 11.0 环境中。战网、Epic 和 GOG 使用共享 CX 引擎及用户单独下载的 Apple GPTK。各客户端的 bottle、账户和游戏分别保留。
-[下载 Soju Mac 应用](https://github.com/BCD1210/soju/releases/download/v1.14.31/Soju-1.14.31-macos-arm64.zip):原生桌面预览版在一个窗口中管理已安装和已拥有的游戏、商店搜索、收藏、游戏启动和平台管理。[安装说明与要求](docs/DESKTOP.md)。
+[下载 Soju Mac 应用](https://github.com/BCD1210/soju/releases/download/v1.14.32/Soju-1.14.32-macos-arm64.zip):原生桌面预览版在一个窗口中管理已安装和已拥有的游戏、商店搜索、收藏、游戏启动和平台管理。[安装说明与要求](docs/DESKTOP.md)。
## 日常维护
diff --git a/VERSION b/VERSION
index 0c491ce6abc..d613550671f 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.14.31
+1.14.32
diff --git a/docs/DESKTOP.md b/docs/DESKTOP.md
index d8b03b0052b..558f28785ff 100644
--- a/docs/DESKTOP.md
+++ b/docs/DESKTOP.md
@@ -1,6 +1,6 @@
# Soju for Mac
-[Download v1.14.31](https://github.com/BCD1210/soju/releases/download/v1.14.31/Soju-1.14.31-macos-arm64.zip)
+[Download v1.14.32](https://github.com/BCD1210/soju/releases/download/v1.14.32/Soju-1.14.32-macos-arm64.zip)
1. Unzip and move **Soju.app** into Applications or ~/Applications.
2. Open **Platforms** to install or open Battle.net, Steam, Epic Games or GOG GALAXY.
diff --git a/docs/privacy.html b/docs/privacy.html
index 12912a64062..38212cd19c9 100644
--- a/docs/privacy.html
+++ b/docs/privacy.html
@@ -29,7 +29,7 @@
<a href="sponsor.html">Advertise</a>
</div></nav>
<main id="main">
-<header class="hero"><h1>Privacy</h1><p class="lead">Soju is a Mac app made by Didim Labs. It keeps your game library on your Mac. This page lists everything that leaves it.</p></header><section id="signin" aria-labelledby="signin-title"><h2 id="signin-title">Signing in with Apple or Google</h2><ul><li>We ask Apple or Google only for your email address. We don&#x27;t ask for contacts, files or anything else.</li><li>Soju asks you to sign in before buying a game or getting a demo in the Didim Labs Store. We use that email to find games you bought from us through Polar, and hand the license keys back to your copy of Soju.</li><li>Our server keeps the sign-in result for at most 10 minutes, then deletes it. Soju keeps your email and keys on your Mac (keys in the macOS Keychain).</li><li>Your Didim Labs account is that email, the provider (Apple or Google) and the days you first and last signed in. We keep it so your games and demos stay with you; a purchase made from Soju uses the same email. Write to us to delete it.</li><li>If you use Apple&#x27;s Hide My Email, we only see the relay address, so purchases made with your real email won&#x27;t be found.</li></ul></section><section id="purchases" aria-labelledby="purchases-title"><h2 id="purchases-title">Buying games</h2><p>Payments go through <a href="https://polar.sh/legal/privacy">Polar</a>, which acts as the seller of record and handles card details, receipts and taxes. We see your email, name, country and what you bought. We never see card numbers.</p></section><section id="app" aria-labelledby="app-title"><h2 id="app-title">What the Soju app sends</h2><ul><li>Soju downloads the store list and the sponsor card from didimlabs.com, and game files from Polar or GitHub.</li><li>When it opens, Soju asks GitHub for the list of Soju releases to tell you if a newer version is out. The request says nothing about you or your games.</li><li>Account connections you add (Steam, GOG and others) talk to those services directly from your Mac.</li><li>If you turn on TV &amp; iPad streaming, Soju installs Sunshine (open source, LizardByte) on your Mac. It streams only to devices you pair with a PIN on your own network, keeps its settings page on your Mac, and only contacts GitHub to check for new versions.</li><li>Play counts (on unless you turn them off): Soju sends which games are installed (once a day) and how many minutes a game stayed open, with your Mac model, chip, macOS and Soju version and a random id made on your Mac. No account, email, name or file path. We use it only to see which games run, and publish no one&#x27;s data. Turn it off under Platforms (Share which games I play) or with soju stats off.</li><li>Soju has no ads tracking or crash reporting.</li></ul></section><section id="site" aria-labelledby="site-title"><h2 id="site-title">This website</h2><p>didimlabs.com runs on Cloudflare, which keeps standard request logs. Pages load Cloudflare Web Analytics, which counts page views and load times without cookies and without identifying you. The site sets no cookies. If you send the advertising form, we get what you type and reply by email.</p></section><section id="news" aria-labelledby="news-title"><h2 id="news-title">Release news emails</h2><p>If you type your email to hear about our next game, we keep that address only for that. We send an email when a new game comes out and nothing else. Write to [email protected] to be removed.</p></section><section id="contact" aria-labelledby="contact-title"><h2 id="contact-title">Questions or deletion</h2><p>Email <a href="mailto:[email protected]">[email protected]</a>. We can tell you what we hold and delete it, except records Polar must keep for tax law. To remove everything from your Mac, sign out in Soju and delete the app.</p></section><section id="ko" aria-labelledby="ko-title"><h2 id="ko-title">개인정보 처리 (요약)</h2><p>디딤랩스 스토어에서 게임을 사거나 데모를 받을 때 애플·구글 로그인을 합니다. 이메일 주소만 받아, Polar에서 그 이메일로 산 게임의 라이선스 키를 찾는 데 한 번 씁니다. 로그인 결과는 서버에 최대 10분만 남고, 디딤랩스 계정으로 이메일·로그인 방식·처음과 마지막 로그인 날짜를 보관합니다. 소주에서 결제할 때도 같은 이메일을 씁니다. 결제 정보는 Polar가 처리하며 우리는 카드 번호를 보지 않습니다. 소주 앱은 설치한 게임 목록(하루 한 번)과 게임별 플레이 시간을 맥 기종·macOS·소주 버전, 맥에서 만든 무작위 번호와 함께 보냅니다. 계정, 이메일, 이름, 파일 경로는 보내지 않고, 어떤 게임이 되는지 보는 데만 쓰고 개인별 기록은 공개하지 않습니다. Platforms의 Share which games I play나 soju stats off로 끌 수 있습니다. 웹사이트는 쿠키 없이 방문 수와 로딩 속도만 세는 Cloudflare Web Analytics를 씁니다. 출시 알림을 신청한 이메일은 새 게임 소식에만 씁니다. 문의와 삭제 요청: [email protected]</p></section>
+<header class="hero"><h1>Privacy</h1><p class="lead">Soju is a Mac app made by Didim Labs. It keeps your game library on your Mac. This page lists everything that leaves it.</p></header><section id="signin" aria-labelledby="signin-title"><h2 id="signin-title">Signing in with Apple or Google</h2><ul><li>We ask Apple or Google only for your email address. We don&#x27;t ask for contacts, files or anything else.</li><li>Soju asks you to sign in before buying a game or getting a demo in the Didim Labs Store. We use that email to find games you bought from us through Polar, and hand the license keys back to your copy of Soju.</li><li>Our server keeps the sign-in result for at most 10 minutes, then deletes it. Soju keeps your email and keys on your Mac (keys in the macOS Keychain).</li><li>Your Didim Labs account is that email, the provider (Apple or Google) and the days you first and last signed in. We keep it so your games and demos stay with you; a purchase made from Soju uses the same email. Write to us to delete it.</li><li>If you use Apple&#x27;s Hide My Email, we only see the relay address, so purchases made with your real email won&#x27;t be found.</li></ul></section><section id="purchases" aria-labelledby="purchases-title"><h2 id="purchases-title">Buying games</h2><p>Payments go through <a href="https://polar.sh/legal/privacy">Polar</a>, which acts as the seller of record and handles card details, receipts and taxes. We see your email, name, country and what you bought. We never see card numbers.</p></section><section id="app" aria-labelledby="app-title"><h2 id="app-title">What the Soju app sends</h2><ul><li>Soju downloads the store list and the sponsor card from didimlabs.com, and game files from Polar or GitHub.</li><li>When it opens, Soju asks GitHub for the list of Soju releases to tell you if a newer version is out. The request says nothing about you or your games.</li><li>Account connections you add (Steam, GOG and others) talk to those services directly from your Mac.</li><li>If you turn on TV &amp; iPad streaming, Soju installs Sunshine (open source, LizardByte) on your Mac. It streams only to devices you pair with a PIN on your own network, keeps its settings page on your Mac, and only contacts GitHub to check for new versions.</li><li>Play counts (on unless you turn them off): Soju sends which games are installed (once a day) and, each time a game is started from Soju or from Steam's window, whether it ran, closed within a minute or never appeared, and how many minutes it stayed open, with your Mac model, chip, macOS and Soju version and a random id made on your Mac. No account, email, name or file path. We use it only to see which games run, and publish no one&#x27;s data. Turn it off under Platforms (Share which games I play) or with soju stats off.</li><li>Soju has no ads tracking or crash reporting.</li></ul></section><section id="site" aria-labelledby="site-title"><h2 id="site-title">This website</h2><p>didimlabs.com runs on Cloudflare, which keeps standard request logs. Pages load Cloudflare Web Analytics, which counts page views and load times without cookies and without identifying you. The site sets no cookies. If you send the advertising form, we get what you type and reply by email.</p></section><section id="news" aria-labelledby="news-title"><h2 id="news-title">Release news emails</h2><p>If you type your email to hear about our next game, we keep that address only for that. We send an email when a new game comes out and nothing else. Write to [email protected] to be removed.</p></section><section id="contact" aria-labelledby="contact-title"><h2 id="contact-title">Questions or deletion</h2><p>Email <a href="mailto:[email protected]">[email protected]</a>. We can tell you what we hold and delete it, except records Polar must keep for tax law. To remove everything from your Mac, sign out in Soju and delete the app.</p></section><section id="ko" aria-labelledby="ko-title"><h2 id="ko-title">개인정보 처리 (요약)</h2><p>디딤랩스 스토어에서 게임을 사거나 데모를 받을 때 애플·구글 로그인을 합니다. 이메일 주소만 받아, Polar에서 그 이메일로 산 게임의 라이선스 키를 찾는 데 한 번 씁니다. 로그인 결과는 서버에 최대 10분만 남고, 디딤랩스 계정으로 이메일·로그인 방식·처음과 마지막 로그인 날짜를 보관합니다. 소주에서 결제할 때도 같은 이메일을 씁니다. 결제 정보는 Polar가 처리하며 우리는 카드 번호를 보지 않습니다. 소주 앱은 설치한 게임 목록(하루 한 번)과 게임별 플레이 시간을 맥 기종·macOS·소주 버전, 맥에서 만든 무작위 번호와 함께 보냅니다. 계정, 이메일, 이름, 파일 경로는 보내지 않고, 어떤 게임이 되는지 보는 데만 쓰고 개인별 기록은 공개하지 않습니다. Platforms의 Share which games I play나 soju stats off로 끌 수 있습니다. 웹사이트는 쿠키 없이 방문 수와 로딩 속도만 세는 Cloudflare Web Analytics를 씁니다. 출시 알림을 신청한 이메일은 새 게임 소식에만 씁니다. 문의와 삭제 요청: [email protected]</p></section>
</main>
<footer><div class="inner">
<p><span>Didim Labs · <a href="mailto:[email protected]">[email protected]</a> · <a href="https://github.com/BCD1210/soju">GitHub</a></span></p>
diff --git a/scripts/game-library.py b/scripts/game-library.py
index 35cd5c72efe..f84781ff0a0 100644
--- a/scripts/game-library.py
+++ b/scripts/game-library.py
@@ -23,6 +23,8 @@ FOLDERS = {'steam': 'steam-bottle', 'epic': 'epic-bottle',
# Steam games that stop without Apple GPTK (soju steam-gptk on): Overwatch 2, and
# Diablo II: Resurrected, whose loader needs GPTK's libd3dshared.
STEAM_GPTK_GAMES = {'2357570', '2536520'}
+# Installed by Steam itself, not games: Steamworks Common Redistributables.
+STEAM_TOOLS = {'228980'}
CLIENTS = {
'steam': 'Program Files (x86)/Steam/steam.exe',
'epic': 'Program Files/Epic Games/Launcher/Portal/Binaries/Win64/EpicGamesLauncher.exe',
@@ -207,6 +209,7 @@ class Library:
uid = item['appid']
if not uid.isdigit() or f.stem != 'appmanifest_' + uid:
raise ValueError('mismatched Steam app ID')
+ if uid in STEAM_TOOLS: continue # installed with Steam itself, not a game
location = case_path(root / 'steamapps/common', PureWindowsPath(item['installdir']).parts)
if PureWindowsPath(item['installdir']).drive: raise ValueError('invalid relative path')
artroot = client / 'appcache/librarycache'
diff --git a/scripts/play-stats.py b/scripts/play-stats.py
index 6b2e63e7641..06541eccbf1 100755
--- a/scripts/play-stats.py
+++ b/scripts/play-stats.py
@@ -4,6 +4,9 @@
soju stats play <library id> --launcher L --title T --path P [--pid N]
Waits for the game to start, counts the minutes it stays open, then sends the
game, its store and the minutes, with the Mac model, chip, macOS and Soju version.
+ Also sends how the start went: ran, quick_exit (closed within a minute) or no_start.
+ soju stats watch
+ While Steam runs, counts games started from Steam's own window the same way.
soju stats library
Which games are installed (library id, title, store), only when that list changed.
soju stats on | off | status
@@ -95,6 +98,18 @@ def running(found, pid=None):
def track(found, pid=None, clock=time.monotonic, sleep=time.sleep, poll=POLL):
"""Minutes the game was open, 0 if it never started."""
+ return track_run(found, pid, clock, sleep, poll)[1]
+
+
+def outcome(started, minutes):
+ """How a start went: the game never appeared, closed within about a minute, or ran."""
+ if not started:
+ return "no_start"
+ return "ran" if minutes >= 1 else "quick_exit"
+
+
+def track_run(found, pid=None, clock=time.monotonic, sleep=time.sleep, poll=POLL):
+ """(started, minutes): whether the game appeared at all, and how long it stayed open."""
begun = clock()
first = last = None
misses = 0
@@ -107,14 +122,87 @@ def track(found, pid=None, clock=time.monotonic, sleep=time.sleep, poll=POLL):
misses = 0
elif first is None:
if now - begun > START_WITHIN:
- return 0
+ return False, 0
else:
misses += 1
if misses >= GONE_AFTER:
break
if first is not None and now - first > MAX_HOURS * 3600:
break
- return int((last - first + poll) // 60)
+ return True, int((last - first + poll) // 60)
+
+
+def report(game, title, launcher, started, minutes, how):
+ """One start: its outcome always, and the minutes when there were any."""
+ item = {"game": game[:120], "title": title[:120], "launcher": launcher[:20]}
+ send({"kind": "launch", "games": [dict(item, result=outcome(started, minutes), how=how)]})
+ if minutes >= 1:
+ send({"kind": "play", "games": [dict(item, minutes=min(minutes, MAX_HOURS * 60))]})
+
+
+STEAM_PROCESS = "\\steam\\steam.exe"
+STEAM_GRACE = 5 * 60 # Steam may take this long to show its window
+
+
+def steam_games(snapshot):
+ """Installed Steam games with the strings their processes carry."""
+ out = {}
+ for g in snapshot.get("games", []):
+ if g.get("platform") != "steam" or not installed(g):
+ continue
+ found = needles(g.get("install_path"))
+ if found:
+ out[g["id"]] = (g.get("title", ""), found)
+ return out
+
+
+def load_snapshot():
+ try:
+ return json.loads((BASE / "logs/library-scan.log").read_text())
+ except (OSError, ValueError):
+ return {}
+
+
+def watch(clock=time.monotonic, sleep=time.sleep, poll=POLL, table=None, snapshot=load_snapshot, deliver=report):
+ """While Steam runs, count the games started from Steam's own window. A game that the
+ library's Play button is already counting (its lock is held) is left to that count."""
+ table = table or (lambda: run("ps", "-axww", "-o", "command=").lower())
+ begun = clock()
+ games, seen, missing, polls = {}, {}, 0, 0
+ try:
+ while True:
+ if polls % 15 == 0:
+ games = steam_games(snapshot())
+ polls += 1
+ sleep(poll)
+ now = clock()
+ lines = table().splitlines()
+ missing = 0 if any(STEAM_PROCESS in line for line in lines) else missing + 1
+ for gid, (title, found) in games.items():
+ up = any(n in line for line in lines for n in found)
+ st = seen.get(gid)
+ if up and st is None:
+ lock = claim(gid)
+ if lock is not None:
+ seen[gid] = {"first": now, "last": now, "misses": 0, "lock": lock, "title": title}
+ elif up:
+ st["last"], st["misses"] = now, 0
+ elif st is not None:
+ st["misses"] += 1
+ if st["misses"] >= GONE_AFTER:
+ finish(gid, seen.pop(gid), poll, deliver)
+ if missing >= GONE_AFTER and now - begun > STEAM_GRACE:
+ break
+ if now - begun > 24 * 3600:
+ break
+ finally:
+ for gid in list(seen):
+ finish(gid, seen.pop(gid), poll, deliver)
+
+
+def finish(gid, st, poll, deliver):
+ st["lock"].unlink(missing_ok=True)
+ deliver(gid, st["title"], "steam", True, int((st["last"] - st["first"] + poll) // 60), "steam")
def post(body):
@@ -197,6 +285,7 @@ def main(argv):
p.add_argument("--path", default="")
p.add_argument("--pid", type=int)
sub.add_parser("library")
+ sub.add_parser("watch")
for name in ("on", "off", "status"):
sub.add_parser(name)
a = ap.parse_args(argv)
@@ -229,6 +318,15 @@ def main(argv):
if send(payload):
stamp.write_text(digest + "\n")
return 0
+ if a.cmd == "watch":
+ lock = claim("steam-watch")
+ if lock is None:
+ return 0 # Steam is already being watched
+ try:
+ watch()
+ finally:
+ lock.unlink(missing_ok=True)
+ return 0
found = needles(a.path)
pid = a.pid if a.launcher in RUNS_IN_SOJU else None
if not found and not pid:
@@ -237,12 +335,10 @@ def main(argv):
if lock is None:
return 0 # this game is already being counted
try:
- minutes = track(found, pid)
+ started, minutes = track_run(found, pid)
finally:
lock.unlink(missing_ok=True)
- if minutes >= 1:
- send({"kind": "play", "games": [{"game": a.game[:120], "title": a.title[:120], "launcher": a.launcher[:20],
- "minutes": min(minutes, MAX_HOURS * 60)}]})
+ report(a.game, a.title, a.launcher, started, minutes, "soju")
return 0
diff --git a/scripts/play.sh b/scripts/play.sh
index 90480dd79f0..0133a986299 100755
--- a/scripts/play.sh
+++ b/scripts/play.sh
@@ -309,6 +309,9 @@ case "$MODE" in
# wrapper (forces --disable-gpu --single-process) + -no-cef-sandbox
# -cef-single-process. Source: github.com/notpop/steam-on-m1-wine (MIT),
# vendored in third_party/.
+ # Count games started from Steam's own window too (play counts; does nothing when they are off,
+ # and only one watcher runs however often Steam is opened).
+ ( nohup python3 "$(dirname "${BASH_SOURCE[0]}")/play-stats.py" watch >/dev/null 2>&1 & )
if [ "${SOJU_STEAM_GPTK:-0}" = 1 ]; then
# Steam with Apple GPTK: the CX engine plus the cross-process winemac
# (scripts/steam-gptk-engine.sh). Same wrapper and flags as below; games
diff --git a/site-worker/stats.js b/site-worker/stats.js
index 7022903b1f9..7069aefc690 100644
--- a/site-worker/stats.js
+++ b/site-worker/stats.js
@@ -4,6 +4,8 @@
// POST /api/stats {id, kind: "play" | "library", games: [...], mac, chip, macos, soju}
// play: games [{game, title, launcher, minutes}] adds minutes to that install's total for the game
// library: games [{game, title, launcher}] replaces that install's list of installed games
+// launch: games [{game, title, launcher, result, how}] counts one start: result ran | quick_exit | no_start,
+// how soju (the library's Play button) | steam (Steam's own window)
// Nothing is published: the counts are read with wrangler (below).
//
// Read everything: wrangler d1 execute soju-stats --remote --command "select * from plays" -c wrangler.didimlabs.toml
@@ -15,8 +17,11 @@ const LAUNCHERS = new Set(["battlenet", "steam", "epic", "gog", "ea", "rockstar"
const SCHEMA = [
"CREATE TABLE IF NOT EXISTS plays (install TEXT NOT NULL, game TEXT NOT NULL, title TEXT, launcher TEXT, minutes INTEGER NOT NULL DEFAULT 0, sessions INTEGER NOT NULL DEFAULT 0, mac TEXT, chip TEXT, macos TEXT, soju TEXT, updated TEXT, PRIMARY KEY (install, game))",
"CREATE TABLE IF NOT EXISTS hits (address TEXT NOT NULL, hour INTEGER NOT NULL, n INTEGER NOT NULL, PRIMARY KEY (address, hour))",
+ "CREATE TABLE IF NOT EXISTS launches (install TEXT NOT NULL, game TEXT NOT NULL, title TEXT, launcher TEXT, result TEXT NOT NULL, how TEXT NOT NULL, n INTEGER NOT NULL DEFAULT 0, mac TEXT, chip TEXT, macos TEXT, soju TEXT, updated TEXT, PRIMARY KEY (install, game, result, how))",
"CREATE TABLE IF NOT EXISTS library (install TEXT NOT NULL, game TEXT NOT NULL, title TEXT, launcher TEXT, mac TEXT, chip TEXT, macos TEXT, soju TEXT, updated TEXT, PRIMARY KEY (install, game))",
];
+const RESULTS = new Set(["ran", "quick_exit", "no_start"]);
+const HOW = new Set(["soju", "steam"]);
let ready = false, minute = 0, count = 0, perAddress = new Map();
const text = (v, n) => String(v ?? "").replace(/[\u0000-\u001f]/g, " ").trim().slice(0, n);
@@ -44,7 +49,7 @@ export async function stats(request, env, url) {
const id = text(input?.id, 40).toLowerCase();
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id)) return json({ error: "Bad id." }, 400);
const kind = input.kind;
- if (kind !== "play" && kind !== "library") return json({ error: "Bad kind." }, 400);
+ if (kind !== "play" && kind !== "library" && kind !== "launch") return json({ error: "Bad kind." }, 400);
const db = env.STATS;
await schema(db);
// Exact per-address limit across Cloudflare's machines: a Mac sends a few requests a day.
@@ -55,11 +60,19 @@ export async function stats(request, env, url) {
if ((hit?.n || 0) > 30) return json({ error: "Busy, try later." }, 429);
const machine = [text(input.mac, 40), text(input.chip, 60), text(input.macos, 20), text(input.soju, 20)];
const now = new Date().toISOString();
- const games = (Array.isArray(input.games) ? input.games : []).slice(0, kind === "play" ? 5 : 200)
- .map((g) => ({ game: text(g?.game, 120), title: text(g?.title, 120), launcher: text(g?.launcher, 20), minutes: Math.floor(Number(g?.minutes)) }))
- .filter((g) => g.game && LAUNCHERS.has(g.launcher) && (kind === "library" || (g.minutes >= 1 && g.minutes <= 720)));
+ const games = (Array.isArray(input.games) ? input.games : []).slice(0, kind === "library" ? 200 : 5)
+ .map((g) => ({ game: text(g?.game, 120), title: text(g?.title, 120), launcher: text(g?.launcher, 20), minutes: Math.floor(Number(g?.minutes)),
+ result: text(g?.result, 12), how: text(g?.how, 8) }))
+ .filter((g) => g.game && LAUNCHERS.has(g.launcher) && (kind === "library" ||
+ (kind === "launch" ? RESULTS.has(g.result) && HOW.has(g.how) : g.minutes >= 1 && g.minutes <= 720)));
if (!games.length) return json({ ok: true });
- if (kind === "play") {
+ if (kind === "launch") {
+ await db.batch(games.map((g) => db.prepare(
+ "INSERT INTO launches (install, game, title, launcher, result, how, n, mac, chip, macos, soju, updated) VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?) " +
+ "ON CONFLICT (install, game, result, how) DO UPDATE SET n = n + 1, title = excluded.title, mac = excluded.mac, chip = excluded.chip, " +
+ "macos = excluded.macos, soju = excluded.soju, updated = excluded.updated",
+ ).bind(id, g.game, g.title, g.launcher, g.result, g.how, ...machine, now)));
+ } else if (kind === "play") {
await db.batch(games.map((g) => db.prepare(
"INSERT INTO plays (install, game, title, launcher, minutes, sessions, mac, chip, macos, soju, updated) VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?) " +
"ON CONFLICT (install, game) DO UPDATE SET minutes = minutes + excluded.minutes, sessions = sessions + 1, title = excluded.title, " +
diff --git a/tests/test_library.py b/tests/test_library.py
index 4d2eee42d90..79a36e8c95b 100644
--- a/tests/test_library.py
+++ b/tests/test_library.py
@@ -68,6 +68,12 @@ class LibraryTests(unittest.TestCase):
db.execute('INSERT INTO Products VALUES (?, ?)', (uid, name))
return database
+ def test_steam_tools_are_not_listed_as_games(self):
+ self.steam(uid='228980', title='Steamworks Common Redistributables', folder='Steamworks Shared')
+ self.steam(uid='123')
+ ids = [g['id'] for g in self.lib.scan()['games']]
+ self.assertEqual(ids, ['steam:123'])
+
def test_four_platforms_and_launch_argv(self):
self.steam(); self.epic(); self.bnet(); database = self.gog()
before = database.read_bytes()
diff --git a/tests/test_play_stats.py b/tests/test_play_stats.py
index 3e3b1a215f2..06e408dadeb 100644
--- a/tests/test_play_stats.py
+++ b/tests/test_play_stats.py
@@ -98,6 +98,53 @@ class PlayStats(unittest.TestCase):
first.write_text('999999') # a count that died without cleaning up
self.assertIsNotNone(ps.claim('steam:1'))
+ def test_track_run_tells_a_start_that_never_happened_from_a_quick_exit(self):
+ clock = Clock()
+ with mock.patch.object(ps, 'running', lambda found, pid=None: False):
+ self.assertEqual(ps.track_run(['x'], clock=clock.now, sleep=clock.sleep, poll=60), (False, 0))
+ clock = Clock()
+ up = iter([True, False, False, False])
+ with mock.patch.object(ps, 'running', lambda found, pid=None: next(up)):
+ self.assertEqual(ps.track_run(['x'], clock=clock.now, sleep=clock.sleep, poll=20), (True, 0))
+ self.assertEqual([ps.outcome(False, 0), ps.outcome(True, 0), ps.outcome(True, 5)], ['no_start', 'quick_exit', 'ran'])
+
+ def test_every_start_reports_its_outcome_and_minutes_only_when_there_are_some(self):
+ sent = []
+ with mock.patch.object(ps, 'send', side_effect=lambda p: sent.append(p) or True):
+ ps.report('steam:1', 'A', 'steam', True, 0, 'soju')
+ ps.report('steam:1', 'A', 'steam', True, 7, 'steam')
+ self.assertEqual([p['kind'] for p in sent], ['launch', 'launch', 'play'])
+ self.assertEqual(sent[0]['games'][0]['result'], 'quick_exit')
+ self.assertEqual((sent[1]['games'][0]['result'], sent[1]['games'][0]['how']), ('ran', 'steam'))
+ self.assertEqual(sent[2]['games'][0]['minutes'], 7)
+
+ def test_watch_counts_games_started_from_steam_and_leaves_play_button_counts_alone(self):
+ snap = {'games': [
+ {'id': 'steam:1', 'platform': 'steam', 'title': 'A', 'install_path': '/b/drive_c/Program Files (x86)/Steam/steamapps/common/A'},
+ {'id': 'steam:2', 'platform': 'steam', 'title': 'B', 'install_path': '/b/drive_c/Program Files (x86)/Steam/steamapps/common/B'},
+ {'id': 'gog:3', 'platform': 'gog', 'title': 'C', 'install_path': '/g/drive_c/C'}]}
+ steam = 'c:\\program files (x86)\\steam\\steam.exe -no-cef-sandbox'
+ a = 'c:\\program files (x86)\\steam\\steamapps\\common\\a\\a.exe'
+ b = 'c:\\program files (x86)\\steam\\steamapps\\common\\b\\b.exe'
+ frames = [steam] * 2 + [steam + '\n' + a + '\n' + b] * 10 + [steam] * 4 + [''] * 4
+ it = iter(frames)
+ clock, got = Clock(), []
+ with tempfile.TemporaryDirectory() as d, mock.patch.object(ps, 'BASE', Path(d)), \
+ mock.patch.object(ps, 'STEAM_GRACE', 0):
+ held = ps.claim('steam:2') # the Play button is already counting B
+ ps.watch(clock=clock.now, sleep=clock.sleep, poll=20, table=lambda: next(it, ''),
+ snapshot=lambda: snap, deliver=lambda *x: got.append(x))
+ self.assertTrue(held.exists())
+ self.assertFalse((Path(d) / 'stats-running' / 'steam-1.pid').exists())
+ self.assertEqual(got, [('steam:1', 'A', 'steam', True, 3, 'steam')])
+
+ def test_watch_stops_when_steam_is_gone(self):
+ clock = Clock()
+ with tempfile.TemporaryDirectory() as d, mock.patch.object(ps, 'BASE', Path(d)), \
+ mock.patch.object(ps, 'STEAM_GRACE', 60):
+ ps.watch(clock=clock.now, sleep=clock.sleep, poll=20, table=lambda: '', snapshot=lambda: {}, deliver=None)
+ self.assertLess(clock.t, 200)
+
if __name__ == '__main__':
unittest.main()
diff --git a/tests/test_stats_worker.mjs b/tests/test_stats_worker.mjs
new file mode 100644
index 00000000000..13ecb7c2206
--- /dev/null
+++ b/tests/test_stats_worker.mjs
@@ -0,0 +1,40 @@
+// The play-count endpoint (site-worker/stats.js) against a stand-in D1 that records statements.
+import test from "node:test";
+import assert from "node:assert/strict";
+import { stats } from "../site-worker/stats.js";
+
+function fakeDb() {
+ const ran = [];
+ const stmt = (sql) => ({ sql, args: [], bind(...a) { this.args = a; return this; }, async first() { ran.push(this); return { n: 1 }; }, async run() { ran.push(this); return {}; } });
+ return { ran, prepare: stmt, async batch(list) { ran.push(...list); return []; } };
+}
+const id = "3f2b8a10-1111-4222-8333-944455556666";
+const post = (body, ip) => new Request("https://didimlabs.com/api/stats", {
+ method: "POST", headers: { "content-type": "application/json", "cf-connecting-ip": ip }, body: JSON.stringify(body) });
+
+test("a launch is counted once per install, game, result and how", async () => {
+ const db = fakeDb();
+ const res = await stats(post({ id, kind: "launch", soju: "1.14.32", games: [
+ { game: "steam:1", title: "A", launcher: "steam", result: "quick_exit", how: "soju" }] }, "10.0.0.1"), { STATS: db });
+ assert.equal(res.status, 200);
+ const insert = db.ran.find((s) => s.sql.startsWith("INSERT INTO launches"));
+ assert.ok(insert, "launch row written");
+ assert.deepEqual(insert.args.slice(0, 6), [id, "steam:1", "A", "steam", "quick_exit", "soju"]);
+});
+
+test("unknown results, ways of starting and kinds are refused or ignored", async () => {
+ const db = fakeDb();
+ await stats(post({ id, kind: "launch", games: [{ game: "steam:1", launcher: "steam", result: "exploded", how: "soju" },
+ { game: "steam:2", launcher: "steam", result: "ran", how: "terminal" }] }, "10.0.0.2"), { STATS: db });
+ assert.equal(db.ran.filter((s) => s.sql.startsWith("INSERT INTO launches")).length, 0);
+ const res = await stats(post({ id, kind: "crash", games: [] }, "10.0.0.3"), { STATS: fakeDb() });
+ assert.equal(res.status, 400);
+});
+
+test("play minutes still need to be between 1 and 720", async () => {
+ const db = fakeDb();
+ await stats(post({ id, kind: "play", games: [{ game: "steam:1", launcher: "steam", minutes: 0 },
+ { game: "steam:2", launcher: "steam", minutes: 5 }] }, "10.0.0.4"), { STATS: db });
+ const plays = db.ran.filter((s) => s.sql.startsWith("INSERT INTO plays"));
+ assert.deepEqual(plays.map((s) => s.args[1]), ["steam:2"]);
+});