mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 13:55:58 +00:00
fix: Steam no longer restarts every launch to import added games, and asks first (#1795)
This commit is contained in:
1 parent
ee3876b965
commit
23bb361006
40 files changed
+405
-7
No files matched your search
@@ -14,6 +14,7 @@ import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
STATE = ".droiddeck-games.json"
|
||||
TRIED = ".droiddeck-import-tried.json"
|
||||
WINNATIVE = ".winnative-steam/steamapps"
|
||||
LIBRARY = "/mnt/droiddeck-sd"
|
||||
LEGACY_LIBRARY = "/mnt/bannerlator-sd"
|
||||
@@ -179,10 +180,44 @@ def request_restart(steam_root):
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
|
||||
|
||||
|
||||
def ask_restart(names, timeout=600, clock=None, sleep=None):
|
||||
"""The app asks whether to restart the client now; anything but "now" leaves the import to the next start."""
|
||||
clock, sleep = clock or time.monotonic, sleep or time.sleep
|
||||
folder = Path(os.environ.get("HOME", "/root"), ".cache/droiddeck")
|
||||
ask, answer = folder / "steam-import.json", folder / "steam-import.answer"
|
||||
token = str(time.time_ns())
|
||||
answer.unlink(missing_ok=True)
|
||||
save_json(ask, {"token": token, "games": names})
|
||||
try:
|
||||
deadline = clock() + timeout
|
||||
while clock() < deadline:
|
||||
reply = read_json(answer, None)
|
||||
if isinstance(reply, dict) and reply.get("token") == token:
|
||||
return reply.get("choice") == "now"
|
||||
sleep(1)
|
||||
return False
|
||||
finally:
|
||||
ask.unlink(missing_ok=True)
|
||||
answer.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def unimported(steam_root, snapshot, candidates):
|
||||
routes = read_json(Path(steam_root) / "userdata" / snapshot["account"] / "config/.droiddeck-routes.json", {})
|
||||
config = Path(steam_root) / "userdata" / snapshot["account"] / "config"
|
||||
routes = read_json(config / ".droiddeck-routes.json", {})
|
||||
routed = set(routes.values()) if isinstance(routes, dict) else set()
|
||||
return sorted({appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True} - routed)
|
||||
tried = read_json(config / TRIED, [])
|
||||
tried = {appid for appid in tried if isinstance(appid, int)} if isinstance(tried, list) else set()
|
||||
owned = {appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True}
|
||||
if tried - routed != tried:
|
||||
save_json(config / TRIED, sorted(tried - routed))
|
||||
return sorted(owned - routed - tried)
|
||||
|
||||
|
||||
def remember_tried(steam_root, account, appids):
|
||||
config = Path(steam_root) / "userdata" / account / "config"
|
||||
tried = read_json(config / TRIED, [])
|
||||
tried = {appid for appid in tried if isinstance(appid, int)} if isinstance(tried, list) else set()
|
||||
save_json(config / TRIED, sorted(tried | set(appids)))
|
||||
|
||||
|
||||
def watch(steam_root, listing):
|
||||
@@ -193,7 +228,7 @@ def watch(steam_root, listing):
|
||||
next_lookup = 0
|
||||
last_status = None
|
||||
probed, next_probe, failures = None, 0, 0
|
||||
pending, requested = [], []
|
||||
pending, requested, account = [], [], None
|
||||
while True:
|
||||
now = time.monotonic()
|
||||
for game in games:
|
||||
@@ -233,6 +268,7 @@ def watch(steam_root, listing):
|
||||
snapshot["sources"] = sources
|
||||
save_json(Path(steam_root) / "userdata" / snapshot["account"] / "config" / STATE, snapshot)
|
||||
pending = unimported(steam_root, snapshot, candidates)
|
||||
account = snapshot["account"]
|
||||
status = "matched %d/%d games; %d owned" % (len(candidates), len(games), sum(snapshot["owned"].values()))
|
||||
except (OSError, ValueError, KeyError, StopIteration, subprocess.TimeoutExpired) as error:
|
||||
status = "ownership check unavailable: " + str(error)
|
||||
@@ -242,9 +278,14 @@ def watch(steam_root, listing):
|
||||
status = last_status
|
||||
if pending and pending != requested and not game_running() and downloads_idle(steam_root):
|
||||
requested = pending
|
||||
print("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
|
||||
names = sorted({game["name"] for game in games if candidates.get(game["folder"]) in pending})
|
||||
try:
|
||||
request_restart(steam_root)
|
||||
remember_tried(steam_root, account, pending)
|
||||
if ask_restart(names) and not game_running() and downloads_idle(steam_root):
|
||||
print("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
|
||||
request_restart(steam_root)
|
||||
else:
|
||||
print("droiddeck-steam-games: %s will be imported the next time the client starts" % pending, flush=True)
|
||||
except (OSError, subprocess.TimeoutExpired) as error:
|
||||
print("droiddeck-steam-games: restart unavailable: %s" % error, flush=True)
|
||||
if status != last_status:
|
||||
@@ -436,6 +477,7 @@ def route(steam_root, acct, games):
|
||||
if seed_install(steam_root, game, appid):
|
||||
routes[str(game["appid"])] = appid
|
||||
continue
|
||||
print(f"droiddeck-steam-games: {game.get('name', appid)} stays a shortcut this session: it could not be linked as Steam app {appid}")
|
||||
except OSError as error:
|
||||
print(f"droiddeck-steam-games: import unavailable ({error})")
|
||||
elif isinstance(appid, int) and 0 < appid < 0x80000000 and seeded(steamapps, game, appid):
|
||||
|
||||
@@ -113,9 +113,11 @@ class ImportsTest(unittest.TestCase):
|
||||
listing = self.root / 'games.json'
|
||||
listing.write_text(json.dumps([self.game]))
|
||||
from unittest.mock import Mock
|
||||
idle = imports.downloads_idle
|
||||
result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True})))
|
||||
with patch.object(imports, 'identify', side_effect=[None, 42]) as identify, \
|
||||
patch.object(imports, 'request_restart'), \
|
||||
patch.object(imports, 'ask_restart', return_value=True), \
|
||||
patch.object(imports, 'time', Mock(monotonic=Mock(side_effect=[0, 301]),
|
||||
sleep=Mock(side_effect=[None, RuntimeError('stop')]))), \
|
||||
patch.object(imports.subprocess, 'run', return_value=result), \
|
||||
@@ -126,7 +128,7 @@ class ImportsTest(unittest.TestCase):
|
||||
snapshot = imports.read_json(self.acct / 'config' / imports.STATE, {})
|
||||
self.assertTrue(snapshot['owned']['42'])
|
||||
|
||||
def run_watch(self, beats, routes=None, busy=False):
|
||||
def run_watch(self, beats, routes=None, busy=False, answer=True, started=False):
|
||||
listing = self.root / 'games.json'
|
||||
listing.write_text(json.dumps([self.game]))
|
||||
if routes is not None:
|
||||
@@ -134,21 +136,64 @@ class ImportsTest(unittest.TestCase):
|
||||
if busy:
|
||||
(self.steam / 'steamapps/downloading/7').mkdir(parents=True)
|
||||
from unittest.mock import Mock
|
||||
idle = imports.downloads_idle
|
||||
result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True})))
|
||||
with patch.object(imports, 'identify', return_value=42), \
|
||||
patch.object(imports, 'game_running', return_value=False), \
|
||||
patch.object(imports, 'request_restart') as restart, \
|
||||
patch.object(imports, 'ask_restart', return_value=answer) as asked, \
|
||||
patch.object(imports, 'downloads_idle', side_effect=lambda root: idle(root) and not (started and asked.called)), \
|
||||
patch.object(imports, 'time', Mock(monotonic=Mock(side_effect=list(range(0, 30 * beats, 30))),
|
||||
sleep=Mock(side_effect=[None] * (beats - 1) + [RuntimeError('stop')]))), \
|
||||
patch.object(imports.subprocess, 'run', return_value=result), \
|
||||
patch('builtins.print'):
|
||||
with self.assertRaisesRegex(RuntimeError, 'stop'):
|
||||
imports.watch(self.steam, listing)
|
||||
self.asked = asked
|
||||
return restart
|
||||
|
||||
def test_newly_owned_game_restarts_the_client_once(self):
|
||||
self.assertEqual(1, self.run_watch(3).call_count)
|
||||
|
||||
def test_an_import_that_did_not_take_restarts_only_once_across_sessions(self):
|
||||
self.assertEqual(1, self.run_watch(3).call_count)
|
||||
self.assertEqual(0, self.run_watch(3).call_count)
|
||||
self.assertEqual([42], imports.read_json(self.acct / 'config' / imports.TRIED, None))
|
||||
|
||||
def test_later_skips_the_restart_and_does_not_ask_again(self):
|
||||
self.assertEqual(0, self.run_watch(3, answer=False).call_count)
|
||||
self.assertEqual([['Example']], [c.args[0] for c in self.asked.call_args_list])
|
||||
self.assertEqual(0, self.run_watch(3).call_count)
|
||||
self.assertEqual(0, self.asked.call_count)
|
||||
|
||||
def test_a_download_started_while_asking_leaves_the_import_for_the_next_start(self):
|
||||
self.assertEqual(0, self.run_watch(3, started=True).call_count)
|
||||
self.assertEqual(1, self.asked.call_count)
|
||||
|
||||
def test_the_app_answers_the_restart_question(self):
|
||||
home = self.root / 'home'
|
||||
folder = home / '.cache/droiddeck'
|
||||
replies = []
|
||||
def sleep(_):
|
||||
ask = json.loads((folder / 'steam-import.json').read_text())
|
||||
replies.append(ask['games'])
|
||||
(folder / 'steam-import.answer').write_text(json.dumps(dict(token=ask['token'], choice=choice)))
|
||||
for choice, expected in (('now', True), ('later', False)):
|
||||
with patch.dict(os.environ, HOME=str(home)):
|
||||
self.assertEqual(expected, imports.ask_restart(['Example'], clock=iter(range(100)).__next__, sleep=sleep))
|
||||
self.assertFalse((folder / 'steam-import.json').exists())
|
||||
self.assertFalse((folder / 'steam-import.answer').exists())
|
||||
self.assertEqual([['Example'], ['Example']], replies)
|
||||
|
||||
def test_no_answer_means_later(self):
|
||||
with patch.dict(os.environ, HOME=str(self.root / 'home')):
|
||||
self.assertFalse(imports.ask_restart(['Example'], timeout=5, clock=iter(range(100)).__next__, sleep=lambda _: None))
|
||||
|
||||
def test_a_tried_import_that_took_is_forgotten(self):
|
||||
imports.save_json(self.acct / 'config' / imports.TRIED, [42])
|
||||
self.assertEqual(0, self.run_watch(2, routes={'1': 42}).call_count)
|
||||
self.assertEqual([], imports.read_json(self.acct / 'config' / imports.TRIED, None))
|
||||
|
||||
def test_imported_game_does_not_restart_the_client(self):
|
||||
self.assertEqual(0, self.run_watch(2, routes={'1': 42}).call_count)
|
||||
|
||||
|
||||
@@ -39,12 +39,16 @@ class X64SignInTest(unittest.TestCase):
|
||||
self.write(self.x64 / 'config/loginusers.vdf', '"users"\n{\n}\n')
|
||||
self.write(self.x64 / 'config/config.vdf', CONFIG % '')
|
||||
self.write(self.home / '.droiddeck-x64/.steam/registry.vdf', REGISTRY % '')
|
||||
self.bin = self.home / 'bin'
|
||||
self.bin.mkdir()
|
||||
(self.bin / 'pgrep').write_text('#!/bin/sh\nexit 1\n')
|
||||
(self.bin / 'pgrep').chmod(0o755)
|
||||
|
||||
def write(self, path, text):
|
||||
path.write_text(text)
|
||||
|
||||
def sync(self):
|
||||
env = dict(os.environ, HOME=str(self.home))
|
||||
env = dict(os.environ, HOME=str(self.home), PATH='%s:%s' % (self.bin, os.environ['PATH']))
|
||||
env.pop('XDG_DATA_HOME', None)
|
||||
env.pop('BL_X64_HOME', None)
|
||||
return subprocess.run(['bash', str(SCRIPT), '--sync-login'], env=env, capture_output=True, text=True, check=True)
|
||||
|
||||
Reference in new issue
Block a user