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.
HTML apple-siliconbattle-netcrossover-alternatived3dmetaldiablo-ii-resurrecteddxmtea-appepic-gamesgame-porting-toolkitgogmac-gamingmacosmacos-gamingrockstar-gamessteamubisoft-connectwhisky-alternativewindows-gameswinewine-wrapper
Xbox PC: first sign-in on a new account (#66)
Mikek40830067d476
diff --git a/app/Accounts.swift b/app/Accounts.swiftindex 4204e86ca26..73e23376803 100644--- a/app/Accounts.swift+++ b/app/Accounts.swift@@ -211,7 +211,7 @@ extension SojuModel {func cancelSignIn() { signInTask?.terminate() }func xboxSignIn(market: String) {guard !accountBusy else { return }- accountBusy = true; accountMessage = "Finish signing in on the Microsoft page that opened…"+ accountBusy = true; accountMessage = "Finish signing in on the Microsoft page that opened. If it stays on \"Please wait\" after an account notice, close it and sign in again."do {let (p, url) = try task(["xbox", "login"], logName: "xbox-account")signInTask = p@@ -224,7 +224,7 @@ extension SojuModel {if process.terminationStatus == 0 { self.syncAccount(.xbox, input: ["market": market]) }else {let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""- self.accountMessage = text.contains("not completed") ? "Sign-in was not completed." : "Sign-in did not finish. Open Diagnostics in Library for details."+ self.accountMessage = text.contains("not completed") ? "Sign-in was not completed. If the page stayed on \"Please wait\" after an account notice, sign in again: Microsoft shows that notice once." : "Sign-in did not finish. Open Diagnostics in Library for details."self.log = String(text.suffix(60000))}}diff --git a/scripts/library-service.py b/scripts/library-service.pyindex b18b5459bb0..3d51180c982 100644--- a/scripts/library-service.py+++ b/scripts/library-service.py@@ -44,11 +44,15 @@ def main():elif args.value == 'gog':games, label = gog_owned(args.base, settings)elif args.value == 'xbox':- games, label = xbox_owned(args.base, settings)+ notices = []+ games, label = xbox_owned(args.base, settings, notices=notices)else:raise ServiceError('Unsupported account provider.')market = settings.get('market') if args.value == 'xbox' else Noneresult = save_account(args.base, args.value, games, label, market or None)+ if args.value == 'xbox' and notices:+ result['message'] += ' ' + ' '.join(notices)+ result['notice'] = notices[0]print(json.dumps(result, ensure_ascii=False))except ServiceError as error:print(json.dumps({'error': str(error)}))diff --git a/scripts/library_services.py b/scripts/library_services.pyindex 940bfd9e086..e52ce293cc3 100644--- a/scripts/library_services.py+++ b/scripts/library_services.py@@ -352,6 +352,16 @@ def gog_owned(base, settings):return list(games.values()), 'Galaxy · …' + selected[-4:]+# xodus-cli reports a failed Xbox Live (XSTS) step this way. A Microsoft account that+# never created an Xbox profile fails here: Xbox Live has no user for it yet.+NO_XBOX_PROFILE = ("This Microsoft account has no Xbox profile yet. Sign in once at xbox.com and "+ "choose a gamertag, then sync again. Downloads need the profile.")+++class XboxProfileMissing(ServiceError):+ pass++def xodus_cli(base):return os.environ.get('SOJU_XODUS_BIN') or str(Path(base) / 'xodus/bin/xodus-cli')@@ -371,6 +381,8 @@ def xodus(base, args, timeout):except OSError:raise ServiceError('The Xbox backend could not start. Run Diagnose in Platforms.') from Noneif result.returncode != 0:+ if re.search(r'unavailable \(xsts\)', result.stderr or ''):+ raise XboxProfileMissing(NO_XBOX_PROFILE)if re.search(r'NEXUS_CREDENTIAL_ERROR_V1 [A-Za-z0-9_-]+', result.stderr or ''):raise ServiceError('Sign in to your Microsoft account in Accounts. Your previous import is unchanged.')raise ServiceError('Xbox did not share your library. Sign in again in Accounts, or retry later. Your previous import is unchanged.')@@ -412,7 +424,7 @@ def entitlement_end(value):SUBSCRIPTION = re.compile(r'CFQ7TTC0[A-Z0-9]{4}')-def xbox_owned(base, settings, deadline=40):+def xbox_owned(base, settings, deadline=40, notices=None):# The app stops a service request after 50 s; every step uses what is left of this budget."""Owned and PC Game Pass games from the signed-in Microsoft account."""started = time.monotonic()@@ -422,6 +434,12 @@ def xbox_owned(base, settings, deadline=40):data = xodus(base, ['library', '--json', '--market', country], timeout=20)if not isinstance(data, dict) or data.get('schema') != 1 or not isinstance(data.get('entitlements'), list):raise ServiceError('Xbox returned an incomplete library. Your previous import is unchanged.')+ if not data['entitlements'] and deadline - (time.monotonic() - started) > 30:+ # Right after sign-in Microsoft can answer with an empty list once; ask again.+ time.sleep(3)+ retry = xodus(base, ['library', '--json', '--market', country], timeout=15)+ if isinstance(retry, dict) and retry.get('schema') == 1 and isinstance(retry.get('entitlements'), list):+ data = retryif len(data['entitlements']) > 10000:raise ServiceError('This library exceeds the supported import size.')now = datetime.datetime.now(datetime.timezone.utc)@@ -458,6 +476,9 @@ def xbox_owned(base, settings, deadline=40):try:profile = xodus(base, ['profile', '--json'], timeout=min(8, left - 1))gamertag = text(profile.get('gamertag'), 40) if isinstance(profile, dict) else ''+ except XboxProfileMissing as error:+ if notices is not None:+ notices.append(str(error))except ServiceError:pass# Art is optional: whatever is not fetched in time is retried on the next sync.diff --git a/scripts/xbox-download.py b/scripts/xbox-download.pyindex 610394435e4..501f6b22879 100755--- a/scripts/xbox-download.py+++ b/scripts/xbox-download.py@@ -19,6 +19,8 @@ CLI = os.environ.get('SOJU_XODUS_BIN') or str(BASE / 'xodus/bin/xodus-cli')GAMES = BASE / 'xbox-bottle/drive_c/XboxGames'MARKETS = ('US', 'KR', 'GB', 'DE', 'JP')MARKER = '.soju-xbox-install.json'+NO_XBOX_PROFILE = ("This Microsoft account has no Xbox profile yet. Sign in once at xbox.com and "+ "choose a gamertag, then download again.")class DownloadError(Exception):@@ -127,7 +129,7 @@ def stream(pid, choice, region, dest):# stderr joins stdout so every backend line goes through clean().process = subprocess.Popen(args, env=environment(), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, text=True, bufsize=1, errors='replace')- phase, shown, busy = None, None, False+ phase, shown, busy, auth = None, None, False, Falsetry:for line in process.stdout:if line.startswith('NEXUS_PROGRESS '):@@ -146,6 +148,7 @@ def stream(pid, choice, region, dest):shown = keyelif line.strip():busy = busy or 'another download is using this folder' in line+ auth = auth or 'Xbox authentication request failed' in lineprint(' ' + clean(line), flush=True)finally:# Stopping Soju's download also stops the backend; its checkpoint stays.@@ -158,9 +161,21 @@ def stream(pid, choice, region, dest):code = process.wait()if busy:raise DownloadError('This game is already downloading. Pause that download first, or wait for it to finish.')+ if auth and code != 0 and not has_xbox_profile():+ raise DownloadError(NO_XBOX_PROFILE)return code == 0 and phase == 'complete'+def has_xbox_profile():+ """False only when Xbox Live has no user for this account (xodus-cli: '(xsts)')."""+ try:+ result = subprocess.run([CLI, 'profile', '--json'], env=environment(), stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=60)+ except (OSError, subprocess.SubprocessError):+ return True+ return not (result.returncode != 0 and 'unavailable (xsts)' in (result.stderr or ''))++def stop(signum, frame):raise KeyboardInterruptdiff --git a/scripts/xbox.sh b/scripts/xbox.shindex be92767aeba..a6073eb141d 100755--- a/scripts/xbox.sh+++ b/scripts/xbox.sh@@ -51,6 +51,7 @@ case "${1:-}" inlogin)need_backendecho "Opening the Microsoft sign-in page. Finish signing in there, then this window closes."+ echo "If Microsoft shows a notice about your account and then stays on \"Please wait\", close the window and sign in again."# Cancel in Soju sends TERM here: close the sign-in window too, so nothing is stored afterwards.# Some backend lines name the account; keep e-mail addresses out of the log."$XODUS_CLI" login > >(sed -E 's/[^[:space:]]+@[^[:space:]]+/<account>/g') 2>&1 &@@ -62,7 +63,14 @@ case "${1:-}" in"$XODUS_CLI" account --json | python3 -c 'import json,sysv=json.load(sys.stdin)sys.exit(0 if v.get("stored") else 1)' || { echo "Sign-in was not completed." >&2; exit 1; }- echo "Signed in." ;;+ echo "Signed in."+ # Xbox Live needs a profile (gamertag) on the account; Microsoft accounts made+ # outside Xbox have none until someone signs in at xbox.com once.+ # Only stderr is kept: stdout carries the account name.+ profile_err="$("$XODUS_CLI" profile --json 2>&1 >/dev/null || true)"+ case "$profile_err" in+ *"unavailable (xsts)"*) echo "This Microsoft account has no Xbox profile yet. Sign in once at xbox.com and choose a gamertag; downloads need it." ;;+ esac ;;logout)# Signing out must work even when the backend is gone or its recipe changed:# any xodus-cli that still runs clears the Keychain entry, and Soju's owndiff --git a/tests/test_xbox.py b/tests/test_xbox.pyindex 32238caeb8c..fb7883b8928 100644--- a/tests/test_xbox.py+++ b/tests/test_xbox.py@@ -703,5 +703,99 @@ class XboxStopAndSignOutTests(unittest.TestCase):self.assertNotIn('install Battle.net, Epic or GOG', (ROOT / 'scripts' / name).read_text(), name)+class XboxFirstSignInTests(unittest.TestCase):+ """What a brand-new Microsoft account runs into on its first Xbox sign-in."""++ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.base = Path(self.temp.name)++ def cli(self, body):+ path = self.base / 'xodus/bin/xodus-cli'+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text('#!/bin/sh\n' + body)+ path.chmod(0o755)+ return path++ ROW = dict(status='Active', isTrial=False, endDate=FUTURE, satisfiedByProductId=None, special=False)+ META = {SILKSONG: dict(title='Silksong', type='Game', windows=True, format='MSIXVC', artwork=None, price='')}++ def test_an_empty_first_answer_is_asked_again_once(self):+ answers = [{'schema': 1, 'entitlements': []},+ {'schema': 1, 'entitlements': [dict(self.ROW, productId=SILKSONG)]}]+ calls = []+ def run(args, **kwargs):+ if args[1] == 'profile':+ return subprocess.CompletedProcess(args, 0, json.dumps({'gamertag': 'Tester'}), '')+ calls.append(args)+ return subprocess.CompletedProcess(args, 0, json.dumps(answers[len(calls) - 1]), '')+ self.cli('exit 0\n')+ with patch.object(svc.subprocess, 'run', side_effect=run), patch.object(svc.time, 'sleep'), \+ patch.object(svc, 'xbox_catalog', return_value=self.META):+ games, label = svc.xbox_owned(self.base, {'market': 'US'})+ self.assertEqual(len(calls), 2)+ self.assertEqual([g['id'] for g in games], ['xbox:' + SILKSONG])++ def test_an_empty_library_is_asked_only_twice(self):+ calls = []+ def run(args, **kwargs):+ if args[1] == 'profile':+ return subprocess.CompletedProcess(args, 0, json.dumps({'gamertag': 'Tester'}), '')+ calls.append(args)+ return subprocess.CompletedProcess(args, 0, json.dumps({'schema': 1, 'entitlements': []}), '')+ self.cli('exit 0\n')+ with patch.object(svc.subprocess, 'run', side_effect=run), patch.object(svc.time, 'sleep'):+ games, _ = svc.xbox_owned(self.base, {'market': 'US'})+ self.assertEqual((len(calls), games), (2, []))++ def test_missing_xbox_profile_is_named_and_the_import_still_saves(self):+ def run(args, **kwargs):+ if args[1] == 'profile':+ return subprocess.CompletedProcess(args, 1, '', 'Xbox profile is temporarily unavailable (xsts); stored account is unchanged.\n')+ return subprocess.CompletedProcess(args, 0, json.dumps({'schema': 1, 'entitlements': [dict(self.ROW, productId=SILKSONG)]}), '')+ self.cli('exit 0\n')+ notices = []+ with patch.object(svc.subprocess, 'run', side_effect=run), patch.object(svc, 'xbox_catalog', return_value=self.META):+ games, label = svc.xbox_owned(self.base, {'market': 'US'}, notices=notices)+ self.assertEqual(len(games), 1)+ self.assertEqual(label, 'Microsoft account')+ self.assertEqual(notices, [svc.NO_XBOX_PROFILE])+ self.assertIn('xbox.com', notices[0])++ def test_download_names_the_missing_xbox_profile(self):+ cli = self.cli('case "$1" in\n'+ ' streaming) echo "Xbox authentication request failed. Check your connection and sign-in."; exit 1 ;;\n'+ ' profile) echo "Xbox profile is temporarily unavailable (xsts); stored account is unchanged." >&2; exit 1 ;;\n'+ 'esac\n')+ game = dict(contentId='807c7d6a-409f-48be-8190-30b09baf7cd4')+ with patch.object(download, 'CLI', str(cli)):+ with self.assertRaisesRegex(download.DownloadError, 'no Xbox profile'):+ download.stream(SILKSONG, game, 'US', self.base)++ def test_download_auth_failure_with_a_profile_is_not_blamed_on_it(self):+ cli = self.cli('case "$1" in\n'+ ' streaming) echo "Xbox authentication request failed. Check your connection and sign-in."; exit 1 ;;\n'+ ' profile) echo \'{"gamertag": "Tester"}\'; exit 0 ;;\n'+ 'esac\n')+ game = dict(contentId='807c7d6a-409f-48be-8190-30b09baf7cd4')+ with patch.object(download, 'CLI', str(cli)):+ self.assertFalse(download.stream(SILKSONG, game, 'US', self.base))++ def test_sign_in_says_when_the_account_has_no_xbox_profile(self):+ cli = self.cli('case "$1" in\n'+ ' login) exit 0 ;;\n'+ ' account) echo \'{"stored": true}\' ;;\n'+ ' profile) echo "Xbox profile is temporarily unavailable (xsts); stored account is unchanged." >&2; exit 1 ;;\n'+ 'esac\n')+ env = dict(os.environ, SOJU_BASE=str(self.base), SOJU_XODUS_BIN=str(cli))+ result = subprocess.run(['/bin/bash', str(ROOT / 'scripts/xbox.sh'), 'login'], env=env,+ capture_output=True, text=True, timeout=30)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn('Signed in.', result.stdout)+ self.assertIn('no Xbox profile', result.stdout)+ self.assertIn('Please wait', result.stdout)++if __name__ == '__main__':unittest.main()