mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 14:26:00 +00:00
feat: add GOG maintenance
This commit is contained in:
1 parent
52fa41767c
commit
198f667bf0
54 files changed
+11840
-26
No files matched your search
@@ -0,0 +1,344 @@
|
||||
#!/usr/bin/python3
|
||||
"""GOG patch installers and the lease shared by maintenance and game launches."""
|
||||
import fcntl
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
BIN = Path(__file__).resolve().parent
|
||||
IDLE = {"wineserver", "services.exe", "winedevice.exe", "explorer.exe", "rpcss.exe", "plugplay.exe",
|
||||
"conhost.exe", "lsass.exe", "svchost.exe", "steam.exe", "wineboot.exe", "winemenubuilder.exe"}
|
||||
|
||||
|
||||
def control(folder):
|
||||
folder = Path(folder).resolve(strict=True)
|
||||
root = folder / ".droiddeck-gog"
|
||||
if root.is_symlink():
|
||||
raise ValueError("GOG control directory is a symbolic link")
|
||||
root.mkdir(exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def read(path):
|
||||
if path.is_symlink():
|
||||
raise ValueError("GOG metadata is a symbolic link")
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def write(path, value):
|
||||
if path.is_symlink():
|
||||
raise ValueError("GOG metadata is a symbolic link")
|
||||
descriptor, name = tempfile.mkstemp(prefix=path.name + ".", suffix=".new", dir=path.parent)
|
||||
temporary = Path(name)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w") as stream:
|
||||
json.dump(value, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
try:
|
||||
os.fsync(directory)
|
||||
except OSError as error:
|
||||
if error.errno not in (errno.EINVAL, errno.ENOTSUP):
|
||||
raise
|
||||
finally:
|
||||
os.close(directory)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def lock_file(root):
|
||||
return os.fdopen(os.open(root / "lease", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600), "r+")
|
||||
|
||||
|
||||
def generation(pid):
|
||||
try:
|
||||
return Path("/proc/%s/stat" % pid).read_text().rsplit(")", 1)[1].split()[19]
|
||||
except (OSError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
def lease(folder, owner):
|
||||
root = control(folder)
|
||||
with lock_file(root) as stream:
|
||||
fcntl.lockf(stream, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
||||
sidecar = read(Path(folder) / ".droiddeck-store.json")
|
||||
if sidecar.get("state", "installed") != "installed":
|
||||
raise ValueError("Resume or recover the GOG update before playing")
|
||||
journal = root / "operation.json"
|
||||
if journal.exists() and read(journal).get("phase") != "download":
|
||||
raise ValueError("GOG maintenance is incomplete")
|
||||
start = generation(owner)
|
||||
if start is None:
|
||||
raise ValueError("Game launcher has exited")
|
||||
print("ready", flush=True)
|
||||
sys.stdout.close()
|
||||
while generation(owner) == start:
|
||||
time.sleep(0.25)
|
||||
return 0
|
||||
|
||||
|
||||
def desktop_environment(base, proc=Path("/proc")):
|
||||
env = dict(base)
|
||||
if env.get("DROIDDECK_GOG_DESKTOP") != "1":
|
||||
return env
|
||||
deadline = time.monotonic() + 45
|
||||
while True:
|
||||
for entry in proc.iterdir():
|
||||
if not entry.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
command = (entry / "cmdline").read_bytes().split(b"\0")[0]
|
||||
if command != b"/usr/bin/plasmashell":
|
||||
continue
|
||||
values = dict(os.fsdecode(item).split("=", 1) for item in (entry / "environ").read_bytes().split(b"\0") if b"=" in item)
|
||||
if values.get("BL_DESKTOP") != "1" or values.get("XDG_RUNTIME_DIR") != env.get("XDG_RUNTIME_DIR"):
|
||||
continue
|
||||
if not values.get("DISPLAY") or values.get("WAYLAND_DISPLAY") == env.get("WAYLAND_DISPLAY"):
|
||||
continue
|
||||
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "BL_DESKTOP"):
|
||||
if key in values:
|
||||
env[key] = values[key]
|
||||
return env
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError("The desktop display is not ready; resume the Linux session and verify recovery before retrying")
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def target_for(folder, appid, game):
|
||||
run = runpy.run_path(str(BIN / "droiddeck-proton-run"))["main"].__globals__
|
||||
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or run["STEAM_ROOT"]
|
||||
target = run["shortcut_target"](str(int(appid) & 0xffffffff), str(game), str(folder), root)
|
||||
target.install = str(folder)
|
||||
return run, root, target
|
||||
|
||||
|
||||
def runner(folder, appid, game, graphical=False):
|
||||
run, root, target = target_for(folder, appid, game)
|
||||
available = run["tools"](root)
|
||||
name, _ = run["choose_tool"](target.appid, run["mapping"](root), available)
|
||||
if name is None:
|
||||
raise ValueError("No Proton tool is installed for this game")
|
||||
tool, command = available[name]
|
||||
base = desktop_environment(os.environ) if graphical else dict(os.environ)
|
||||
env = run["environment"](base, target, tool, root, window=base.get("BL_DESKTOP") == "1")
|
||||
env["DROIDDECK_GOG_MAINTENANCE"] = "1"
|
||||
# Installer copy routines use x87 integer loads/stores; reduced precision corrupts paths (FEX #5827).
|
||||
env["FEX_X87REDUCEDPRECISION"] = "0"
|
||||
env.pop("BL_STORE_EXIT", None)
|
||||
return str(Path(tool) / command), env, target.compatdata
|
||||
|
||||
|
||||
def active(prefix, proc=Path("/proc")):
|
||||
result = []
|
||||
prefix = os.path.realpath(os.path.join(prefix, "pfx"))
|
||||
for entry in proc.iterdir():
|
||||
if not entry.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
env = dict(part.split(b"=", 1) for part in (entry / "environ").read_bytes().split(b"\0") if b"=" in part)
|
||||
if os.path.realpath(os.fsdecode(env.get(b"WINEPREFIX", b""))) != prefix:
|
||||
continue
|
||||
args = (entry / "cmdline").read_bytes().split(b"\0")
|
||||
name = os.fsdecode(args[0]).replace("\\", "/").rsplit("/", 1)[-1].lower()
|
||||
if name not in IDLE:
|
||||
result.append(int(entry.name))
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
return result
|
||||
|
||||
|
||||
def idle(folder, appid, game):
|
||||
_, _, target = target_for(folder, appid, game)
|
||||
if active(target.compatdata):
|
||||
raise ValueError("Close the GOG game before maintenance")
|
||||
return 0
|
||||
|
||||
|
||||
def validate_installer(folder, installer):
|
||||
root = control(folder)
|
||||
path = Path(installer)
|
||||
if path.is_symlink() or not path.resolve(strict=True).is_relative_to(root / "downloads") or path.suffix.lower() != ".exe":
|
||||
raise ValueError("The patch executable is outside GOG download storage")
|
||||
with path.open("rb") as stream:
|
||||
if stream.read(2) != b"MZ":
|
||||
raise ValueError("The GOG patch is not a Windows executable")
|
||||
return path
|
||||
|
||||
|
||||
def installer_arguments(path):
|
||||
with path.open("rb") as stream:
|
||||
data = stream.read(4 * 1024 * 1024)
|
||||
return ["/NOGUI"] if b"Inno Setup Setup Data" in data else []
|
||||
|
||||
|
||||
def start(folder, appid, installer, game):
|
||||
root = control(folder)
|
||||
validate_installer(folder, installer)
|
||||
with lock_file(root) as stream:
|
||||
fcntl.lockf(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
journal = read(root / "operation.json")
|
||||
if journal.get("phase") != "patch-ready":
|
||||
raise ValueError("The patch must be selected again before it can run")
|
||||
idle(folder, appid, game)
|
||||
journal["phase"] = "patch-starting"
|
||||
write(root / "operation.json", journal)
|
||||
write(root / "patch-status.json", {"state": "starting", "startedAt": time.time()})
|
||||
with (root / "patch.log").open("ab") as log:
|
||||
subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "run", folder, appid, installer, game],
|
||||
stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True)
|
||||
return 0
|
||||
|
||||
|
||||
def status(folder):
|
||||
root = control(folder)
|
||||
path = root / "patch-status.json"
|
||||
result = read(path)
|
||||
ended = result.get("state") == "running" and generation(result.get("pid")) != result.get("generation")
|
||||
abandoned = result.get("state") == "starting" and time.time() - result.get("startedAt", 0) > 60
|
||||
if ended or abandoned:
|
||||
result = {"state": "uncertain", "reason": "The patch helper ended without a confirmed result; verify recovery before retrying"}
|
||||
write(path, result)
|
||||
journal = read(root / "operation.json")
|
||||
journal["phase"] = "patch-uncertain"
|
||||
write(root / "operation.json", journal)
|
||||
print(json.dumps(result), flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
def run_patch(folder, appid, installer, game):
|
||||
root = control(folder)
|
||||
try:
|
||||
with lock_file(root) as stream:
|
||||
fcntl.lockf(stream, fcntl.LOCK_EX)
|
||||
path = validate_installer(folder, installer)
|
||||
command, env, prefix = runner(folder, appid, game, True)
|
||||
if active(prefix):
|
||||
raise ValueError("Close the GOG game before applying the patch")
|
||||
journal = read(root / "operation.json")
|
||||
if journal.get("phase") != "patch-starting":
|
||||
raise ValueError("The patch is already running or needs recovery")
|
||||
journal["phase"] = "patch-applying"
|
||||
write(root / "operation.json", journal)
|
||||
sidecar_path = Path(folder) / ".droiddeck-store.json"
|
||||
sidecar = read(sidecar_path)
|
||||
sidecar["state"] = "updating"
|
||||
write(sidecar_path, sidecar)
|
||||
installed_path = root / "installed.json"
|
||||
if installed_path.is_file():
|
||||
installed = read(installed_path)
|
||||
installed.update(verified=False, manifest={}, files=[])
|
||||
write(installed_path, installed)
|
||||
write(root / "patch-status.json", {"state": "running", "pid": os.getpid(), "generation": generation(os.getpid())})
|
||||
os.makedirs(prefix, exist_ok=True)
|
||||
setup = runpy.run_path(str(BIN / "droiddeck-store-launch"))["main"].__globals__
|
||||
previous = dict(os.environ)
|
||||
try:
|
||||
os.environ.update(env)
|
||||
pfx = Path(prefix) / "pfx"
|
||||
if not (pfx / "system.reg").is_file() or not (pfx / "drive_c/windows/system32/reg.exe").is_file():
|
||||
subprocess.run([command, "run", "wineboot.exe", "-u"], env=env, timeout=90, check=True)
|
||||
if not (pfx / "drive_c/windows/system32/reg.exe").is_file():
|
||||
raise ValueError("Proton did not initialize the game's registry tool")
|
||||
result = setup["apply_gog_registry"](Path(folder), prefix, command, installation=journal.get("before"))
|
||||
if not result.startswith(("ready", "written=")):
|
||||
raise ValueError("GOG registry preparation failed; the patch was not applied")
|
||||
prepare_setup(folder, command, env)
|
||||
finally:
|
||||
os.environ.clear(); os.environ.update(previous)
|
||||
proc = subprocess.Popen([command, "run", str(path), *installer_arguments(path)], cwd=str(path.parent), env=env)
|
||||
code = proc.wait()
|
||||
quiet_at = time.monotonic()
|
||||
while True:
|
||||
if active(prefix):
|
||||
quiet_at = time.monotonic()
|
||||
elif time.monotonic() - quiet_at >= 2:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
journal["phase"] = "patch-uncertain"
|
||||
write(root / "operation.json", journal)
|
||||
if code:
|
||||
raise ValueError("GOG patch installer exited with code %d; inspect patch.log" % code)
|
||||
write(root / "patch-status.json", {"state": "done", "exitCode": code})
|
||||
return 0
|
||||
except Exception as error:
|
||||
write(root / "patch-status.json", {"state": "failed", "reason": str(error)})
|
||||
return 1
|
||||
|
||||
|
||||
def prepare_setup(folder, command, env):
|
||||
root = control(folder)
|
||||
record_path = root / "installed.json"
|
||||
if not record_path.is_file():
|
||||
return
|
||||
journal = read(root / "operation.json")
|
||||
record = journal.get("before") or read(record_path)
|
||||
manifest = record.get("manifest", {})
|
||||
if not record.get("build"):
|
||||
return
|
||||
info_path = Path(folder) / ("goggame-%s.info" % record["id"])
|
||||
language = read(info_path).get("language", "") if info_path.is_file() else ""
|
||||
legacy = manifest.get("product", {})
|
||||
products = manifest.get("products", []) if not legacy else [
|
||||
{"productId": str(item["gameID"]), "temp_executable": item["executable"].lstrip("/\\")}
|
||||
for item in legacy.get("support_commands", [])
|
||||
if "Neutral" in item.get("languages", []) or record.get("language") in item.get("languages", []) or language in item.get("languages", [])]
|
||||
for product in products:
|
||||
if str(product.get("productId")) not in record.get("products", []):
|
||||
continue
|
||||
program = None
|
||||
if manifest.get("scriptInterpreter"):
|
||||
if not (Path(folder) / ("goggame-%s.script" % product["productId"])).is_file():
|
||||
continue
|
||||
program = Path(folder) / "support/__redist/ISI/scriptinterpreter.exe"
|
||||
elif product.get("temp_executable"):
|
||||
relative = product["temp_executable"].replace("\\", "/")
|
||||
for candidate in (Path(folder) / "support" / str(product["productId"]) / relative, Path(folder) / relative):
|
||||
if candidate.is_file():
|
||||
program = candidate
|
||||
break
|
||||
if program is None:
|
||||
continue
|
||||
if not program.resolve(strict=True).is_relative_to(Path(folder).resolve()):
|
||||
raise ValueError("GOG setup executable leaves the installation")
|
||||
windows = "Z:" + str(Path(folder).resolve()).replace("/", "\\")
|
||||
args = ["/VERYSILENT", "/DIR=" + windows, "/ProductId=" + str(product["productId"]),
|
||||
"/galaxyclient", "/buildId=" + str(legacy.get("timestamp", record["build"])), "/versionName=" + record.get("version", ""),
|
||||
"/lang-code=" + record.get("language", "en-US"), "/supportDir=" + windows + "\\support", "/nodesktopshortcut"]
|
||||
if language:
|
||||
args += ["/Language=" + language, "/LANG=" + language.lower()]
|
||||
result = subprocess.run([command, "run", str(program), *args], env=env, cwd=folder, timeout=120)
|
||||
if result.returncode:
|
||||
raise ValueError("GOG installation setup failed; the patch was not applied")
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) == 3 and argv[0] == "lease":
|
||||
return lease(argv[1], int(argv[2]))
|
||||
if len(argv) == 4 and argv[0] == "idle":
|
||||
return idle(*argv[1:])
|
||||
if len(argv) == 2 and argv[0] == "status":
|
||||
return status(argv[1])
|
||||
if len(argv) == 5 and argv[0] == "start":
|
||||
return start(*argv[1:])
|
||||
if len(argv) == 5 and argv[0] == "run":
|
||||
return run_patch(*argv[1:])
|
||||
raise ValueError("Invalid GOG maintenance command")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
except Exception as error:
|
||||
print("GOG maintenance: " + str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -40,6 +40,7 @@ import time
|
||||
import subprocess
|
||||
import tempfile
|
||||
import hashlib
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
LAUNCHER = ".droiddeck-launch.bat"
|
||||
@@ -494,8 +495,27 @@ def gog_registry(folder):
|
||||
return entries, skipped
|
||||
|
||||
|
||||
def apply_gog_registry(folder, compat_data, proton, timeout=90):
|
||||
def apply_gog_registry(folder, compat_data, proton, timeout=90, installation=None):
|
||||
entries, skipped = gog_registry(folder)
|
||||
if installation:
|
||||
product = str(installation["id"])
|
||||
if not product.isdigit():
|
||||
raise ValueError("Invalid GOG product identifier")
|
||||
values = {"PATH": windows_path(str(folder))}
|
||||
identity = Path(folder) / ("goggame-%s.id" % product)
|
||||
if identity.is_file():
|
||||
actual = json.loads(identity.read_text(encoding="utf-8-sig")).get("buildId")
|
||||
if actual and installation.get("build") and str(actual) != str(installation["build"]):
|
||||
raise ValueError("GOG build metadata changed before patch setup")
|
||||
if installation.get("build"):
|
||||
values["BUILDID"] = installation["build"]
|
||||
if installation.get("version"):
|
||||
values["VER"] = installation["version"]
|
||||
for key, value in values.items():
|
||||
entry = gog_entry({"root": "HKLM", "subkey": "Software\\GOG.com\\Games\\" + product,
|
||||
"valueName": key, "valueData": value, "valueType": "string"}, {})
|
||||
if entry:
|
||||
entries.append(entry)
|
||||
note = " skipped=%d" % skipped if skipped else ""
|
||||
if not entries:
|
||||
return "none" + note
|
||||
@@ -512,7 +532,8 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90):
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-gog-") as tmp:
|
||||
source = Path(tmp) / "registry.reg"
|
||||
source.write_bytes(b"\xff\xfe" + text.encode("utf-16-le"))
|
||||
run = subprocess.run([proton, "run", "reg.exe", "import", windows_path(str(source)), "/reg:32"],
|
||||
executable = pfx / "drive_c/windows/system32/reg.exe"
|
||||
run = subprocess.run([proton, "run", str(executable) if executable.is_file() else "reg.exe", "import", windows_path(str(source)), "/reg:32"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
|
||||
if run.returncode or not (pfx / "system.reg").is_file():
|
||||
return "import-failed" + note
|
||||
@@ -525,6 +546,8 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90):
|
||||
|
||||
|
||||
def main(argv):
|
||||
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
|
||||
return 0
|
||||
if argv and argv[0] == "--exited":
|
||||
rest, code = argv[1:], 0
|
||||
if rest[:1] == ["--code"] and len(rest) > 1:
|
||||
@@ -543,6 +566,18 @@ def main(argv):
|
||||
return 0
|
||||
folder, sidecar = found
|
||||
store, game = str(sidecar.get("store")), str(sidecar.get("id"))
|
||||
if store == "gog":
|
||||
helper = Path(__file__).resolve().with_name("droiddeck-gog-maintenance")
|
||||
if helper.is_file():
|
||||
child = subprocess.Popen([sys.executable, str(helper), "lease", str(folder), str(os.getppid())],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
|
||||
start_new_session=True)
|
||||
ready = child.stdout.readline().decode().strip()
|
||||
child.stdout.close()
|
||||
threading.Thread(target=child.wait, daemon=True).start()
|
||||
if ready != "ready":
|
||||
log("gog: close or recover the maintenance operation before playing")
|
||||
return RAN_FAILED
|
||||
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
|
||||
prefix_id = os.path.basename(compat_data) if compat_data else ""
|
||||
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
|
||||
|
||||
@@ -76,6 +76,7 @@ def required():
|
||||
for name in ['turnip26.3.0-a6xx', 'turnip26.3.0-quest2']]
|
||||
paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libblsession.so',
|
||||
'libblfastpath.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard',
|
||||
'usr/local/bin/droiddeck-gog-maintenance',
|
||||
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime',
|
||||
'usr/local/lib/droiddeck-pipewire.tzst']]
|
||||
for arch in ['x86_64', 'i386']:
|
||||
|
||||
@@ -30,6 +30,24 @@ def config_text(entries):
|
||||
|
||||
|
||||
class GameDebugLoggingTest(unittest.TestCase):
|
||||
def test_maintenance_precision_survives_run_with_performance_game_settings(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
config = home / ".config/droiddeck/game-environment.json"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(json.dumps({"version": 1, "shared": {"FEX_X87REDUCEDPRECISION": "1"},
|
||||
"games": {"42": {"FEX_X87REDUCEDPRECISION": "1"}}}))
|
||||
probe = home / "proton"
|
||||
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ['FEX_X87REDUCEDPRECISION'])\n")
|
||||
probe.chmod(0o755)
|
||||
base = {**os.environ, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata/42")}
|
||||
maintenance = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "run"],
|
||||
env={**base, "DROIDDECK_GOG_MAINTENANCE": "1", "FEX_X87REDUCEDPRECISION": "0"}, text=True, capture_output=True, check=True)
|
||||
game = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun"],
|
||||
env={**base, "FEX_X87REDUCEDPRECISION": "1"}, text=True, capture_output=True, check=True)
|
||||
self.assertEqual("0", maintenance.stdout.strip())
|
||||
self.assertEqual("1", game.stdout.strip())
|
||||
|
||||
def test_real_game_launch_without_config_file_keeps_the_base_environment(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import contextlib
|
||||
import concurrent.futures
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import sys
|
||||
import stat
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
G = runpy.run_path(str(BIN / "droiddeck-gog-maintenance"))["main"].__globals__
|
||||
|
||||
|
||||
class GogMaintenance(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.folder = Path(self.temp.name)
|
||||
self.control = G["control"](self.folder)
|
||||
(self.folder / ".droiddeck-store.json").write_text(json.dumps({"store": "gog", "id": "1"}))
|
||||
|
||||
def test_only_downloaded_windows_executables_can_be_patches(self):
|
||||
download = self.control / "downloads"
|
||||
download.mkdir()
|
||||
patch = download / "patch.exe"
|
||||
patch.write_bytes(b"MZtest")
|
||||
self.assertEqual(patch, G["validate_installer"](self.folder, patch))
|
||||
outside = self.folder / "outside.exe"
|
||||
outside.write_bytes(b"MZtest")
|
||||
with self.assertRaises(ValueError):
|
||||
G["validate_installer"](self.folder, outside)
|
||||
patch.write_bytes(b"not PE")
|
||||
with self.assertRaises(ValueError):
|
||||
G["validate_installer"](self.folder, patch)
|
||||
|
||||
def test_overlapping_metadata_writes_publish_complete_documents(self):
|
||||
target = self.control / "operation.json"
|
||||
def publish(value):
|
||||
G["write"](target, {"value": value, "payload": str(value) * 10000})
|
||||
result = G["read"](target)
|
||||
self.assertEqual(str(result["value"]) * 10000, result["payload"])
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
list(pool.map(publish, range(32)))
|
||||
self.assertEqual([], list(self.control.glob("*.new")))
|
||||
|
||||
def test_directory_sync_unsupported_by_external_storage_keeps_the_record(self):
|
||||
original = os.fsync
|
||||
def fsync(fd):
|
||||
if stat.S_ISDIR(os.fstat(fd).st_mode):
|
||||
raise OSError(errno.EINVAL, "directory sync unsupported")
|
||||
return original(fd)
|
||||
target = self.control / "operation.json"
|
||||
with mock.patch.object(G["os"], "fsync", side_effect=fsync):
|
||||
G["write"](target, {"phase": "download"})
|
||||
self.assertEqual("download", G["read"](target)["phase"])
|
||||
|
||||
def test_unsuccessful_registry_preparation_never_runs_the_installer(self):
|
||||
download = self.control / "downloads"; download.mkdir()
|
||||
patch = download / "patch.exe"; patch.write_bytes(b"MZtest")
|
||||
prefix = self.folder / "prefix/pfx"
|
||||
(prefix / "drive_c/windows/system32").mkdir(parents=True)
|
||||
(prefix / "drive_c/windows/system32/reg.exe").write_bytes(b"MZreg")
|
||||
(prefix / "system.reg").write_text("registry")
|
||||
for result in ("timeout", "import-failed", "no-proton", "none", "unexpected"):
|
||||
with self.subTest(result=result):
|
||||
G["write"](self.control / "operation.json", {"phase": "patch-starting", "before": {"id": "1"}})
|
||||
def setup_main():
|
||||
pass
|
||||
with mock.patch.dict(setup_main.__globals__, {"apply_gog_registry": lambda *a, **k: result}), \
|
||||
mock.patch.dict(G, {"runner": lambda *a: ("/proton", {}, str(self.folder / "prefix")), "active": lambda *a: []}), \
|
||||
mock.patch.object(G["runpy"], "run_path", return_value={"main": setup_main}), \
|
||||
mock.patch.object(G["subprocess"], "Popen") as spawn:
|
||||
self.assertEqual(1, G["run_patch"](str(self.folder), "1", str(patch), "game.exe"))
|
||||
spawn.assert_not_called()
|
||||
self.assertIn("registry preparation failed", G["read"](self.control / "patch-status.json")["reason"])
|
||||
|
||||
def test_only_recognized_inno_installers_get_the_gog_ui_compatibility_argument(self):
|
||||
path = self.folder / "patch.exe"
|
||||
path.write_bytes(b"MZunknown installer")
|
||||
self.assertEqual([], G["installer_arguments"](path))
|
||||
path.write_bytes(b"MZdata Inno Setup Setup Data (6.2.1)")
|
||||
self.assertEqual(["/NOGUI"], G["installer_arguments"](path))
|
||||
|
||||
def test_game_launch_lease_excludes_updater_and_releases_on_owner_exit(self):
|
||||
import fcntl
|
||||
owner = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])
|
||||
self.addCleanup(lambda: owner.poll() is None and owner.kill())
|
||||
lease = subprocess.Popen([sys.executable, str(BIN / "droiddeck-gog-maintenance"), "lease", str(self.folder), str(owner.pid)],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
self.addCleanup(lease.stdout.close)
|
||||
self.addCleanup(lease.stderr.close)
|
||||
self.addCleanup(lambda: lease.poll() is None and lease.kill())
|
||||
self.assertEqual(b"ready\n", lease.stdout.readline())
|
||||
with G["lock_file"](self.control) as stream:
|
||||
with self.assertRaises(BlockingIOError):
|
||||
fcntl.lockf(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
owner.terminate(); owner.wait()
|
||||
lease.wait(timeout=5)
|
||||
with G["lock_file"](self.control) as stream:
|
||||
fcntl.lockf(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
|
||||
def test_incomplete_update_cannot_launch(self):
|
||||
(self.folder / ".droiddeck-store.json").write_text(json.dumps({"store": "gog", "id": "1", "state": "updating"}))
|
||||
with self.assertRaises(ValueError):
|
||||
G["lease"](self.folder, os.getpid())
|
||||
|
||||
def test_running_game_and_wrong_prefix_are_distinguished(self):
|
||||
proc = self.folder / "proc"
|
||||
for pid, prefix, name in [(10, "/prefix/pfx", "game.exe"), (11, "/other/pfx", "other.exe"), (12, "/prefix/pfx", "services.exe")]:
|
||||
row = proc / str(pid); row.mkdir(parents=True)
|
||||
(row / "environ").write_bytes(b"WINEPREFIX=" + prefix.encode() + b"\0")
|
||||
(row / "cmdline").write_bytes(name.encode() + b"\0")
|
||||
self.assertEqual([10], G["active"]("/prefix", proc))
|
||||
|
||||
def test_desktop_installer_inherits_the_nested_display_not_the_bridge_display(self):
|
||||
proc = self.folder / "proc"
|
||||
row = proc / "10"; row.mkdir(parents=True)
|
||||
(row / "cmdline").write_bytes(b"/usr/bin/plasmashell\0")
|
||||
(row / "environ").write_bytes(b"BL_DESKTOP=1\0XDG_RUNTIME_DIR=/run/session\0WAYLAND_DISPLAY=wayland-1\0DISPLAY=:0\0XAUTHORITY=/run/session/auth\0UNRELATED=value\0")
|
||||
env = G["desktop_environment"]({"DROIDDECK_GOG_DESKTOP": "1", "XDG_RUNTIME_DIR": "/run/session", "WAYLAND_DISPLAY": "wayland-0"}, proc)
|
||||
self.assertEqual("wayland-1", env["WAYLAND_DISPLAY"])
|
||||
self.assertEqual(":0", env["DISPLAY"])
|
||||
self.assertEqual("/run/session/auth", env["XAUTHORITY"])
|
||||
self.assertEqual("1", env["BL_DESKTOP"])
|
||||
self.assertNotIn("UNRELATED", env)
|
||||
|
||||
def test_maintenance_uses_full_x87_precision_without_changing_game_preferences(self):
|
||||
target = mock.Mock(compatdata="/selected/prefix", appid="2526420341")
|
||||
run = {"tools": lambda root: {"selected": ("/selected/proton", "proton")},
|
||||
"mapping": lambda root: {}, "choose_tool": lambda *args: ("selected", None),
|
||||
"environment": lambda env, *args, **kwargs: dict(env)}
|
||||
with mock.patch.dict(G, {"target_for": lambda *args: (run, "/steam", target)}), \
|
||||
mock.patch.dict(os.environ, {"FEX_X87REDUCEDPRECISION": "1"}):
|
||||
command, env, prefix = G["runner"]("/game", "2526420341", "/game/game.exe")
|
||||
self.assertEqual("/selected/proton/proton", command)
|
||||
self.assertEqual("/selected/prefix", prefix)
|
||||
self.assertEqual("0", env["FEX_X87REDUCEDPRECISION"])
|
||||
self.assertEqual("1", os.environ["FEX_X87REDUCEDPRECISION"])
|
||||
|
||||
def test_legacy_setup_uses_authentic_timestamp_and_support_layout(self):
|
||||
program = self.folder / "support/1/setup.exe"
|
||||
program.parent.mkdir(parents=True); program.write_bytes(b"MZtest")
|
||||
record = {"id": "1", "build": "3301", "products": ["1"], "language": "en-US", "manifest": {"product": {
|
||||
"timestamp": 31847977, "support_commands": [{"gameID": "1", "executable": "/setup.exe", "languages": ["English"]}]}}}
|
||||
G["write"](self.control / "installed.json", {"verified": False})
|
||||
G["write"](self.control / "operation.json", {"before": record})
|
||||
G["write"](self.folder / "goggame-1.info", {"language": "English"})
|
||||
with mock.patch.object(G["subprocess"], "run", return_value=mock.Mock(returncode=0)) as run:
|
||||
G["prepare_setup"](str(self.folder), "/proton", {})
|
||||
args = run.call_args.args[0]
|
||||
self.assertEqual(str(program), args[2])
|
||||
self.assertIn("/buildId=31847977", args)
|
||||
self.assertNotIn("/buildId=3301", args)
|
||||
self.assertIn("/Language=English", args)
|
||||
|
||||
def test_interrupted_patch_is_not_started_again(self):
|
||||
(self.control / "operation.json").write_text(json.dumps({"phase": "patch-applying"}))
|
||||
with mock.patch.dict(G, {"validate_installer": lambda *a: self.folder / "patch.exe"}):
|
||||
with self.assertRaises(ValueError):
|
||||
G["start"](str(self.folder), "2147483666", "patch.exe", "game.exe")
|
||||
|
||||
def test_dead_installer_helper_requires_recovery_without_replay(self):
|
||||
G["write"](self.control / "operation.json", {"phase": "patch-applying"})
|
||||
G["write"](self.control / "patch-status.json", {"state": "running", "pid": 99999999, "generation": "123"})
|
||||
with mock.patch.dict(G, {"generation": lambda pid: None}), mock.patch.object(G["subprocess"], "Popen") as spawn:
|
||||
self.assertEqual(0, G["status"](str(self.folder)))
|
||||
self.assertFalse(spawn.called)
|
||||
self.assertEqual("uncertain", G["read"](self.control / "patch-status.json")["state"])
|
||||
self.assertEqual("patch-uncertain", G["read"](self.control / "operation.json")["phase"])
|
||||
|
||||
def test_abandoned_start_and_confirmed_completion_are_distinct(self):
|
||||
G["write"](self.control / "operation.json", {"phase": "patch-starting"})
|
||||
G["write"](self.control / "patch-status.json", {"state": "starting", "startedAt": 10})
|
||||
with mock.patch.object(G["time"], "time", return_value=100):
|
||||
G["status"](str(self.folder))
|
||||
self.assertEqual("uncertain", G["read"](self.control / "patch-status.json")["state"])
|
||||
G["write"](self.control / "patch-status.json", {"state": "done", "exitCode": 0})
|
||||
G["status"](str(self.folder))
|
||||
self.assertEqual({"state": "done", "exitCode": 0}, G["read"](self.control / "patch-status.json"))
|
||||
|
||||
def test_registry_and_installer_use_same_prefix_without_cloud_launch(self):
|
||||
download = self.control / "downloads"; download.mkdir()
|
||||
patch = download / "patch.exe"; patch.write_bytes(b"MZtest")
|
||||
prefix = self.folder / "prefix/pfx"
|
||||
(prefix / "drive_c/windows/system32").mkdir(parents=True)
|
||||
(prefix / "drive_c/windows/system32/reg.exe").write_bytes(b"MZreg")
|
||||
(prefix / "system.reg").write_text("registry")
|
||||
G["write"](self.control / "operation.json", {"phase": "patch-starting"})
|
||||
calls = []
|
||||
setup = {"main": lambda: None}
|
||||
def setup_main():
|
||||
pass
|
||||
setup_main.__globals__["apply_gog_registry"] = lambda *a, **k: calls.append(("registry", a[1])) or "written=1"
|
||||
fake = mock.Mock(); fake.wait.return_value = 0
|
||||
def spawn(argv, **kwargs):
|
||||
self.assertEqual("run", argv[1])
|
||||
self.assertEqual("1", kwargs["env"]["DROIDDECK_GOG_MAINTENANCE"])
|
||||
calls.append(("patch", kwargs["env"]["STEAM_COMPAT_DATA_PATH"]))
|
||||
return fake
|
||||
with mock.patch.dict(G, {"runner": lambda *a: ("/proton", {"STEAM_COMPAT_DATA_PATH": str(self.folder / "prefix"), "DROIDDECK_GOG_MAINTENANCE": "1"}, str(self.folder / "prefix")),
|
||||
"active": lambda *a: []}), \
|
||||
mock.patch.object(G["runpy"], "run_path", return_value={"main": setup_main}), \
|
||||
mock.patch.object(G["subprocess"], "Popen", side_effect=spawn):
|
||||
self.assertEqual(0, G["run_patch"](str(self.folder), "2147483666", str(patch), "game.exe"))
|
||||
self.assertEqual([("registry", str(self.folder / "prefix")), ("patch", str(self.folder / "prefix"))], calls)
|
||||
self.assertEqual("done", G["read"](self.control / "patch-status.json")["state"])
|
||||
self.assertEqual("updating", G["read"](self.folder / ".droiddeck-store.json")["state"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -391,6 +391,30 @@ def set_registry(**arguments):
|
||||
|
||||
|
||||
class GogRegistry(unittest.TestCase):
|
||||
def test_patch_registration_uses_authentic_build_and_the_prefix_registry_executable(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='7')
|
||||
(folder / 'goggame-7.id').write_text(json.dumps({'buildId': 'opaque-0001'}))
|
||||
proton = Path(root) / 'proton'; proton.write_text('selected Proton')
|
||||
data = Path(root) / 'compat'
|
||||
executable = data / 'pfx/drive_c/windows/system32/reg.exe'
|
||||
executable.parent.mkdir(parents=True); executable.write_bytes(b'MZreg')
|
||||
(data / 'pfx/system.reg').write_text('registry')
|
||||
imported = []
|
||||
def run(argv, **kwargs):
|
||||
self.assertEqual([str(proton), 'run', str(executable), 'import'], argv[:4])
|
||||
text = Path(argv[4][2:].replace('\\', '/')).read_bytes()[2:].decode('utf-16-le')
|
||||
imported.append(text)
|
||||
return __import__('subprocess').CompletedProcess(argv, 0)
|
||||
record = {'id': '7', 'build': 'opaque-0001', 'version': 'RC-final'}
|
||||
with patch.object(store.subprocess, 'run', side_effect=run):
|
||||
self.assertTrue(store.apply_gog_registry(folder, str(data), str(proton), installation=record).startswith('written='))
|
||||
self.assertIn('[HKEY_LOCAL_MACHINE\\Software\\GOG.com\\Games\\7]', imported[0])
|
||||
self.assertIn('"BUILDID"="opaque-0001"', imported[0])
|
||||
self.assertIn('"VER"="RC-final"', imported[0])
|
||||
with self.assertRaises(ValueError):
|
||||
store.apply_gog_registry(folder, str(data), str(proton), installation=dict(record, build='invented'))
|
||||
|
||||
def test_the_scripts_registry_values_are_read_with_the_games_paths(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1454587428')
|
||||
|
||||
Reference in new issue
Block a user