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: download games to an external drive; release v1.9.0 (#74)
Mikeke74931f3178f
diff --git a/README.ko.md b/README.ko.mdindex 641e6e8da7c..5222c289710 100644--- a/README.ko.md+++ b/README.ko.md@@ -81,7 +81,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.8.2/Soju-1.8.2-macos-arm64.zip): 네이티브 앱 프리뷰에서 설치된 게임과 보유 게임, 스토어 검색, 즐겨찾기, 게임 실행, 플랫폼 관리를 한 화면에서 다룰 수 있습니다. [설치 안내와 요구 사항](docs/DESKTOP.md)을 확인해 주세요.+[Soju 맥 앱 다운로드](https://github.com/BCD1210/soju/releases/download/v1.9.0/Soju-1.9.0-macos-arm64.zip): 네이티브 앱 프리뷰에서 설치된 게임과 보유 게임, 스토어 검색, 즐겨찾기, 게임 실행, 플랫폼 관리를 한 화면에서 다룰 수 있습니다. [설치 안내와 요구 사항](docs/DESKTOP.md)을 확인해 주세요.## 일상 명령diff --git a/README.md b/README.mdindex 78d0bd2e3f1..7968ffa2170 100644--- a/README.md+++ b/README.md@@ -25,7 +25,7 @@ CodeWeavers' published sources; Steam uses a separate private Wine 11 setup.Apple's proprietary GPTK/D3DMetal is downloaded separately. Games and storeclients are not included.-**Current release: [v1.8.2](https://github.com/BCD1210/soju/releases/tag/v1.8.2).**+**Current release: [v1.9.0](https://github.com/BCD1210/soju/releases/tag/v1.9.0).**The compatibility examples below were verified on M4 Pro / macOS 26.5.D2R and Hogwarts Legacy are examples of supported games, not the scope of the project.@@ -101,7 +101,7 @@ soju install # then: soju battlenet / soju d2r / soju steam / soju epic / soThe 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.8.2/Soju-1.8.2-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.9.0/Soju-1.9.0-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@@ -179,10 +179,11 @@ soju xbox-install # build the backend (installs rustup/protobuf withsoju xbox-login # Microsoft's own sign-in page in a windowsoju xbox-sync US # import owned + Game Pass games (US, KR, GB, DE, JP)soju xbox-download 9N116V0599HB # download by Store product ID; run again to resume+soju xbox-location /Volumes/T7 # download new games to an external drive (--default: back to this Mac)soju xbox-logout # sign out; downloaded games stay```-- Downloads go to `~/.battlenet-macos/xbox-bottle/drive_c/XboxGames/<ProductId>` and resume from where they stopped.+- Downloads go to `~/.battlenet-macos/xbox-bottle/drive_c/XboxGames/<ProductId>` and resume from where they stopped. To save space on the Mac, choose a folder on an external drive in **Accounts → Xbox PC → Change…** (or `soju xbox-location`). The drive can be APFS, Mac OS Extended or exFAT (most external SSDs come as exFAT); FAT, NTFS and network drives are refused. Games already downloaded stay where they are, an unfinished download resumes in its own folder, and a game whose drive is unplugged stays in the library as "Drive not connected" until you plug it in again (Soju never downloads it to the Mac instead). A renamed drive is found again.- Only GDK games in the MSIXVC format can be downloaded. Games packaged as MSIXVC2 are marked *Not supported* ([xodus#53](https://github.com/xodus-gaming/xodus/issues/53)).- The Microsoft sign-in is stored in the macOS Keychain as "Xodus Service". macOS may ask to allow access after a backend rebuild. Soju stores game IDs, titles, package format, box art and your Xbox gamertag (as the account label), never the account e-mail or tokens.- The owned-library list comes from the same Microsoft endpoint the Xbox PC app uses. If Microsoft changes it, the import fails and the previous import is kept.diff --git a/README.zh.md b/README.zh.mdindex 4e26003e493..9c726970aeb 100644--- a/README.zh.md+++ b/README.zh.md@@ -85,7 +85,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.8.2/Soju-1.8.2-macos-arm64.zip):原生桌面预览版在一个窗口中管理已安装和已拥有的游戏、商店搜索、收藏、游戏启动和平台管理。[安装说明与要求](docs/DESKTOP.md)。+[下载 Soju Mac 应用](https://github.com/BCD1210/soju/releases/download/v1.9.0/Soju-1.9.0-macos-arm64.zip):原生桌面预览版在一个窗口中管理已安装和已拥有的游戏、商店搜索、收藏、游戏启动和平台管理。[安装说明与要求](docs/DESKTOP.md)。## 日常维护diff --git a/VERSION b/VERSIONindex 53adb84c822..f8e233b2733 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.8.2+1.9.0diff --git a/app/Accounts.swift b/app/Accounts.swiftindex 73e23376803..2c241a331c4 100644--- a/app/Accounts.swift+++ b/app/Accounts.swift@@ -96,6 +96,44 @@ extension SojuModel {syncAccount(.steam, input: ["snapshot": value])} catch { accountMessage = error.localizedDescription }}+ /// Choose where new Xbox PC downloads go: a folder on an APFS external drive, or the default on this Mac.+ func chooseXboxLocation(useDefault: Bool = false) {+ guard !accountBusy else { return }+ var folder = "--default"+ if !useDefault {+ let panel = NSOpenPanel()+ panel.title = "Choose where Xbox PC games are downloaded"+ panel.message = "Pick a folder on an external drive (APFS, Mac OS Extended or exFAT). Games already downloaded stay where they are."+ panel.prompt = "Use This Folder"+ panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true+ panel.directoryURL = URL(fileURLWithPath: "/Volumes")+ guard panel.runModal() == .OK, let url = panel.url else { return }+ folder = url.path+ // Read the folder here so macOS asks now whether Soju may use this drive,+ // not later in the middle of a library scan.+ _ = try? FileManager.default.contentsOfDirectory(atPath: url.path)+ }+ do {+ accountBusy = true; accountMessage = "Checking the download location…"+ let (p, url) = try task(["xbox", "location", folder], logName: "xbox-location")+ p.terminationHandler = { [weak self] process in+ let output = (try? String(contentsOf: url, encoding: .utf8)) ?? ""+ let lines = output.split(separator: "\n").map { $0.replacingOccurrences(of: "soju: ", with: "") }+ DispatchQueue.main.async {+ guard let self else { return }+ self.accountBusy = false+ self.accountMessage = process.terminationStatus == 0+ ? lines.joined(separator: " ")+ : (lines.last ?? "Could not use that folder for Xbox downloads.")+ self.refreshLibrary()+ }+ }+ try p.run()+ } catch {+ accountBusy = false+ accountMessage = "Could not change the download location: " + error.localizedDescription+ }+ }func forgetAccount(_ platform: Launcher) {guard !accountBusy else { return }do {@@ -242,6 +280,13 @@ struct AccountsView: View {@State private var userTask: Process?@State private var usersMessage = ""@AppStorage("soju.store.region") private var market = "US"+ private var xboxLocationText: String {+ guard let location = model.xboxLocation else { return "Downloads go to this Mac." }+ var text = location.isDefault ? "Downloads go to this Mac" : "Downloads go to " + location.volume + " (" + location.path + ")"+ if !location.available { return text + " · drive not connected" }+ if let free = location.freeBytes { text += " · " + ByteCountFormatter.string(fromByteCount: free, countStyle: .file) + " free" }+ return text+ }@State private var confirmDisconnect = falseprivate func summary(_ platform: Launcher) -> AccountSummary? { model.accountSummaries.first { $0.platform == platform } }var body: some View {@@ -319,6 +364,19 @@ struct AccountsView: View {.buttonStyle(.borderedProminent).disabled(model.accountBusy || !model.installed.contains(.xbox))}}+ if model.installed.contains(.xbox) {+ HStack(spacing: 10) {+ Label(xboxLocationText, systemImage: model.xboxLocation?.isDefault == false ? "externaldrive" : "internaldrive")+ .font(.callout).foregroundStyle(model.xboxLocation?.available == false ? .orange : .secondary)+ .lineLimit(2).textSelection(.enabled)+ Spacer()+ Button("Change…") { model.chooseXboxLocation() }.disabled(model.accountBusy)+ .help("Download new Xbox PC games to a folder on an external drive (APFS, Mac OS Extended or exFAT).")+ if model.xboxLocation?.isDefault == false {+ Button("Use This Mac") { model.chooseXboxLocation(useDefault: true) }.disabled(model.accountBusy)+ }+ }+ }}.padding(12)}HStack(spacing: 12) {diff --git a/app/Library.swift b/app/Library.swiftindex 01826f423dc..23d1b9e34c4 100644--- a/app/Library.swift+++ b/app/Library.swift@@ -11,13 +11,18 @@ struct InstalledGame: Decodable, Identifiable {let owned: Bool?let downloaded: Bool?let format: String?+ /// Xbox PC: false while the external drive holding the download is not connected.+ let available: Bool?+ /// Xbox PC: the drive the download is on ("this Mac" for the internal disk).+ let volume: String?+ var isOnUnpluggedDrive: Bool { platform == .xbox && available == false }/// Xbox PC: a folder with an unfinished download is not installed yet.var isInstalled: Bool { platform == .xbox ? downloaded == true : !installPath.isEmpty }var isPartialDownload: Bool { platform == .xbox && !installPath.isEmpty && downloaded != true }/// Owned but not downloadable (for example MSIXVC2 packages).var downloadBlocked: Bool { platform == .xbox && !isInstalled && !isPartialDownload && issue != nil }enum CodingKeys: String, CodingKey {- case id, platform, title, artwork, issue, owned, downloaded, format+ case id, platform, title, artwork, issue, owned, downloaded, format, available, volumecase installPath = "install_path"}}@@ -26,6 +31,24 @@ struct LibrarySnapshot: Decodable {let accounts: [AccountSummary]?let games: [InstalledGame]let warnings: [String]+ let xboxLocation: XboxLocation?+ enum CodingKeys: String, CodingKey {+ case accounts, games, warnings+ case xboxLocation = "xbox_location"+ }+}+/// Where new Xbox PC downloads go (scripts/xbox_locations.py describe()).+struct XboxLocation: Decodable, Equatable {+ let path: String+ let volume: String+ let isDefault: Bool+ let available: Bool+ let freeBytes: Int64?+ enum CodingKeys: String, CodingKey {+ case path, volume, available+ case isDefault = "default"+ case freeBytes = "free_bytes"+ }}struct LibraryPreferences: Codable {var favorites: Set<String> = []@@ -64,6 +87,7 @@ extension SojuModel {if process.terminationStatus == 0, let result {self.games = result.games; self.scanWarnings = result.warningsself.accountSummaries = result.accounts ?? []+ self.xboxLocation = result.xboxLocation} else {self.scanWarnings = ["Could not refresh your library. Check that Python 3 is installed, then retry."]}@@ -74,7 +98,7 @@ extension SojuModel {guard let self, let p, self.scanner === p, p.isRunning else { return }p.terminate()self.scanning = false; self.scanner = nil- self.scanWarnings = ["Scanning took too long. Reconnect any external game drives and refresh."]+ self.scanWarnings = ["Scanning took too long. If macOS asks whether Soju may access a drive or folder, answer it; reconnect any external game drives, then refresh."]}} catch {scanner = nil; scanning = false@@ -434,7 +458,7 @@ struct LibraryView: View {.overlay(RoundedRectangle(cornerRadius: 14).stroke(Color.primary.opacity(0.07), lineWidth: 1)).contextMenu {Button("Show details") { selected = game }- Button("Show in Finder") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: game.installPath) }.disabled(!game.isInstalled)+ Button("Show in Finder") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: game.installPath) }.disabled(!game.isInstalled || game.isOnUnpluggedDrive)if game.platform.opensAWindow {Button("Open " + game.platform.title) { model.launch(game.platform) }.disabled(model.busy)}@@ -463,12 +487,20 @@ struct LibraryView: View {return parts.count > 1 ? parts.dropFirst().joined(separator: " · ") : progress}if game.platform == .xbox {+ if game.isOnUnpluggedDrive { return "Drive not connected" }if game.isPartialDownload { return "Paused" }if game.downloadBlocked { return "Not supported" }}return !game.isInstalled ? "Not installed" : issue == nil ? "Installed" : "Needs attention"}+ private func installedLabel(_ game: InstalledGame) -> String {+ guard game.isInstalled else { return "Owned · not installed" }+ if let volume = game.volume, volume != "this Mac" {+ return game.isOnUnpluggedDrive ? "On " + volume + " · drive not connected" : "Installed on " + volume+ }+ return "Installed on this Mac"+ }private func diagnose(_ game: InstalledGame) {selected = nilmodel.run(["game-doctor", game.id], title: "Checking " + game.title + "…")@@ -481,7 +513,7 @@ struct LibraryView: View {VStack(alignment: .leading, spacing: 13) {Text(game.platform.title).font(.system(size: 11, weight: .semibold)).foregroundStyle(game.platform.accent)Text(game.title).font(.system(size: 24, weight: .bold, design: .rounded))- Label(game.isInstalled ? "Installed on this Mac" : "Owned · not installed", systemImage: game.isInstalled ? "internaldrive" : "cloud").font(.system(size: 12)).foregroundStyle(.secondary)+ Label(installedLabel(game), systemImage: !game.isInstalled ? "cloud" : game.volume.map { $0 != "this Mac" } == true ? "externaldrive" : "internaldrive").font(.system(size: 12)).foregroundStyle(.secondary)Text(game.platform == .xbox ? "Downloaded from the Microsoft Store. Xbox PC support is experimental: not every game works. The first launch may download about 600 MB of Xbox runtime files and take a few minutes to set up." : "Opens through " + game.platform.title + ". You may need to sign in or finish an update in the launcher.").font(.system(size: 12)).foregroundStyle(.secondary)if game.downloadBlocked, let issue = game.issue {@@ -496,7 +528,7 @@ struct LibraryView: View {}}HStack {- Button("Show files") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: game.installPath) }.disabled(!game.isInstalled)+ Button("Show files") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: game.installPath) }.disabled(!game.isInstalled || game.isOnUnpluggedDrive)Button("Diagnose") { diagnose(game) }.disabled(model.busy)if game.platform.opensAWindow {Button("Open " + game.platform.title) { model.launch(game.platform) }.disabled(model.busy)diff --git a/app/Soju.swift b/app/Soju.swiftindex af325799be8..6c9eec26270 100644--- a/app/Soju.swift+++ b/app/Soju.swift@@ -68,6 +68,7 @@ enum Launcher: String, CaseIterable, Identifiable {@Published var games: [InstalledGame] = []@Published var scanning = false@Published var scanWarnings: [String] = []+ @Published var xboxLocation: XboxLocation?@Published var launchingGames: Set<String> = []@Published var stoppingGames: Set<String> = []@Published var libraryIssue: String?diff --git a/docs/ACCOUNTS.md b/docs/ACCOUNTS.mdindex e6dbcf13a2f..6228ff9639e 100644--- a/docs/ACCOUNTS.md+++ b/docs/ACCOUNTS.md@@ -55,6 +55,7 @@ If the database is busy, incomplete or has an unsupported schema, the previous iSoju saves product IDs, titles, package format, box art and the Xbox gamertag (shown as the account label). It does not save the account e-mail. The sign-in itselfstays in the macOS Keychain ("Xodus Service"); **Sign Out…** signs out and removes the import, even when the Xbox PC backend was removed.Owned Xbox games show **Download**. Downloads run beside other work, can be stopped and resume later.+To download to an external drive, use **Change…** next to the download location under Xbox PC and pick a folder on an APFS, Mac OS Extended or exFAT drive. Games on a drive that is not plugged in stay in the library as **Drive not connected**.Games packaged as MSIXVC2 cannot be downloaded yet. **Play** starts a downloaded game on Soju's engine (experimental; needs the CX engine and Apple GPTK). Quitting the game copies its saves back into the game folder.## Use your librarydiff --git a/docs/DESKTOP.md b/docs/DESKTOP.mdindex 53624810e6c..a42d63fbe3c 100644--- a/docs/DESKTOP.md+++ b/docs/DESKTOP.md@@ -1,6 +1,6 @@# Soju for Mac-[Download v1.8.2](https://github.com/BCD1210/soju/releases/download/v1.8.2/Soju-1.8.2-macos-arm64.zip)+[Download v1.9.0](https://github.com/BCD1210/soju/releases/download/v1.9.0/Soju-1.9.0-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/index.html b/docs/index.htmlindex 61396b20a80..aa39b62b159 100644--- a/docs/index.html+++ b/docs/index.html@@ -124,7 +124,7 @@ its own login, purchases, downloads and game updates.</p><section id="install" aria-labelledby="install-title"><h2 id="install-title">Choose your launchers. Get set up.</h2>-<p><a class="btn" href="https://github.com/BCD1210/soju/releases/download/v1.8.2/Soju-1.8.2-macos-arm64.zip">Download Soju for Mac</a></p>+<p><a class="btn" href="https://github.com/BCD1210/soju/releases/download/v1.9.0/Soju-1.9.0-macos-arm64.zip">Download Soju for Mac</a></p><p>The native desktop preview combines installed and imported owned games, searches stores and manages all four launchers.Apple Silicon · app UI: macOS 14+ · Steam component build: macOS 26+.<a href="https://github.com/BCD1210/soju/blob/main/docs/DESKTOP.md">Setup and signing notes</a>.</p>diff --git a/scripts/desktop-action.sh b/scripts/desktop-action.shindex 85fbaa51dab..e3cb6cefdd1 100755--- a/scripts/desktop-action.sh+++ b/scripts/desktop-action.sh@@ -21,6 +21,7 @@ case "$ACTION" in*) echo "Unknown VR action."; exit 64 ;; esac ;;xbox)case "${1:-}" in login|logout|kill|status) exec bash "$ROOT/scripts/xbox.sh" "$1" ;;+ location) exec bash "$ROOT/scripts/xbox.sh" location "${2:?Choose a folder}" ;;*) echo "Unknown Xbox action."; exit 64 ;; esac ;;install)export SOJU_PLATFORMS="${1:?Choose at least one launcher}"diff --git a/scripts/doctor.sh b/scripts/doctor.shindex c8fd65ff6d2..b59a7e84ccd 100755--- a/scripts/doctor.sh+++ b/scripts/doctor.sh@@ -152,11 +152,22 @@ elif [ "$CHECK_XBOX" = 1 ]; thenn=$(python3 -c 'import json,sys;print(len(json.load(open(sys.argv[1]))["games"]))' "$BASE/account-libraries/xbox.json" 2>/dev/null || echo "?")info "imported Xbox library: $n games"fi- partial=0- for d in "$BASE"/xbox-bottle/drive_c/XboxGames/*/; do- [ -f "$d.nexus-streaming-v1.jsonl" ] && [ ! -f "$d.soju-xbox-install.json" ] && partial=$((partial+1))- done- [ "$partial" = 0 ] || warn "$partial unfinished Xbox download(s): download again to resume"+ # Download folders (the Mac and external drives); paths are printed with ~ for the home folder.+ while IFS="$(printf '\t')" read -r level text; do+ case "$level" in warn) warn "$text" ;; *) info "$text" ;; esac+ done < <(SOJU_BASE="$BASE" python3 "$ROOT/scripts/xbox_locations.py" json 2>/dev/null | python3 -c '+import json, sys+try:+ v = json.load(sys.stdin)+except ValueError:+ sys.exit(0)+print("info\tXbox downloads go to " + v["current"]["path"] + ("" if v["current"]["available"] else " (not connected)"))+partial = sum(r["partial"] for r in v["roots"])+if partial: print("warn\t" + str(partial) + " unfinished Xbox download(s): download again to resume")+for r in v["roots"]:+ if not r["connected"]: print("warn\tXbox game drive not connected: " + r["volume"])+for w in v["warnings"]: print("info\t" + w)+')python3 "$ROOT/scripts/fetch-xbox-runtime.py" --check && pass "Xbox game runtime DLLs verified" \|| info "Xbox game runtime not downloaded yet (first Play or soju xbox-install fetches it)"python3 "$ROOT/scripts/xbox-prefix.py" --check && pass "Xbox prefix ready to play" \diff --git a/scripts/game-library.py b/scripts/game-library.pyindex e113c4b3cf6..efeabe467b5 100644--- a/scripts/game-library.py+++ b/scripts/game-library.py@@ -14,6 +14,7 @@ import syssys.path.insert(0, str(Path(__file__).resolve().parent))from game_artwork import executable_iconfrom library_services import saved_accounts+import xbox_locationsfrom urllib.parse import quoteFOLDERS = {'steam': 'steam-bottle', 'epic': 'epic-bottle',@@ -287,21 +288,32 @@ class Library:self.warn('gog', 'An installation record could not be read. Verify this game in Galaxy.')def xbox(self):- games = self.base / FOLDERS['xbox'] / 'drive_c/XboxGames'- if not games.is_dir(): return- for location in sorted(p for p in games.iterdir() if p.is_dir()):- uid = location.name- if not re.fullmatch(r'[A-Z0-9]{12}', uid): continue+ # Downloads may be on the Mac or on external drives (xbox_locations.py); a game whose+ # drive is unplugged stays listed as downloaded but not available.+ locations = xbox_locations+ locations.BASE, locations.DEFAULT = self.base, self.base / FOLDERS['xbox'] / 'drive_c/XboxGames'+ locations.STATE = self.base / 'xbox-locations.json'+ notes = []+ found = locations.scan(warnings=notes)+ for note in notes: self.warn('xbox', note)+ index = locations.load()['games']+ for uid, (location, kind) in sorted(found.items()):try:- record = location / '.soju-xbox-install.json'- if record.is_file():- item = read_json(record)+ art = first_file([self.base / 'library-artwork' / ('xbox-' + uid + '.jpg')])+ if kind == 'missing':+ title = index.get(uid, {}).get('title') or uid+ issue = locations.not_connected(location)+ self.games['xbox:' + uid] = dict(id='xbox:' + uid, platform='xbox', title=title.strip()[:300],+ install_path=str(location / uid), artwork=art, issue=issue,+ arguments=['run', uid], downloaded=True, available=False,+ volume=locations.volume_name(location))+ continue+ if kind == 'complete':+ item = read_json(location / '.soju-xbox-install.json')if item.get('schema') != 1 or item.get('product_id') != uid: raise ValueError('mismatched Xbox ID')title, ready = item.get('title') or uid, True- elif (location / '.nexus-streaming-v1.jsonl').is_file():+ else:title, ready = uid, False- else: continue- art = first_file([self.base / 'library-artwork' / ('xbox-' + uid + '.jpg')])self.add('xbox', uid, title, location, ['run', uid], art, ready)game = self.games['xbox:' + uid]if not ready:@@ -312,6 +324,8 @@ class Library:if not os.access(engine / 'bin/wine', os.X_OK): game['issue'] = XBOX_ENGINEelif not (engine / 'lib/external/libd3dshared.dylib').is_file(): game['issue'] = XBOX_GPTKgame['downloaded'] = ready+ game['available'] = True+ game['volume'] = locations.volume_name(location.parent)except (OSError, ValueError, KeyError, TypeError, AttributeError):self.warn('xbox', 'A download record could not be read. Download the game again to repair it.')@@ -335,7 +349,11 @@ class Library:self.games[game['id']] = dict(game, arguments=[])return {'accounts': accounts, 'games': [{k: v for k, v in g.items() if k != 'arguments'}for g in sorted(self.games.values(), key=lambda g: (g['title'].casefold(), g['id']))],- 'warnings': self.warnings}+ 'warnings': self.warnings, 'xbox_location': self.xbox_location()}++ def xbox_location(self):+ try: return xbox_locations.describe()+ except (OSError, ValueError, KeyError, TypeError): return Nonedef command(self, game_id, install=False):self.scan()@@ -343,6 +361,8 @@ class Library:if game is None: raise ValueError('This game is no longer installed. Refresh the library.')root = Path(__file__).resolve().parentif game['platform'] == 'xbox':+ # A game on an unplugged drive is never downloaded again onto the Mac.+ if game.get('available') is False: raise ValueError(game['issue'])if install:if game.get('downloaded'): raise ValueError('This game is already downloaded. Use Play instead.')if game.get('owned') is not True and not game['install_path']: raise ValueError('This game is not in your Xbox library.')diff --git a/scripts/soju b/scripts/sojuindex 1ec09b195c5..616b220d60d 100755--- a/scripts/soju+++ b/scripts/soju@@ -44,6 +44,7 @@ Usage:soju xbox-logout Sign out (downloaded games are kept)soju xbox-sync [US|KR|GB|DE|JP] Import your owned and PC Game Pass gamessoju xbox-download <ProductId> Download an owned game (resumable)+ soju xbox-location [<folder>|--default] Where new Xbox downloads go (an external APFS or exFAT drive works)soju xbox-run <ProductId> Play a downloaded game (experimental)soju xbox-kill Stop a running Xbox download or game@@ -80,6 +81,7 @@ case "${1:-}" inxbox-login) exec bash "$ROOT/scripts/xbox.sh" login ;;xbox-logout) shift; exec bash "$ROOT/scripts/xbox.sh" logout "$@" ;;xbox-kill) exec bash "$ROOT/scripts/xbox.sh" kill ;;+ xbox-location) shift; exec bash "$ROOT/scripts/xbox.sh" location "$@" ;;xbox-run) shift; exec python3 "$ROOT/scripts/game-library.py" launch "xbox:${1:?Choose a Store product ID}" ;;xbox-download) shift; exec python3 "$ROOT/scripts/game-library.py" install "xbox:${1:?Choose a Store product ID}" ;;xbox-sync)diff --git a/scripts/uninstall.sh b/scripts/uninstall.shindex 90eb9cd9749..7f37a85f730 100755--- a/scripts/uninstall.sh+++ b/scripts/uninstall.sh@@ -134,5 +134,7 @@ Not removed by this script (they are Homebrew's):brew uninstall protobuf rustup Xodus build dependencies, if Soju installed themIf you kept the Microsoft sign-in, it stays in your Keychain as "Xodus Service"(remove it in Keychain Access).+Xbox games downloaded to an external drive stay on that drive (delete their+folders in Finder if you no longer need them).EOTecho "Done."diff --git a/scripts/xbox-download.py b/scripts/xbox-download.pyindex 501f6b22879..1476db1ce45 100755--- a/scripts/xbox-download.py+++ b/scripts/xbox-download.py@@ -14,9 +14,11 @@ import signalimport subprocessimport sys+sys.path.insert(0, str(Path(__file__).resolve().parent))+import xbox_locations as locations # noqa: E402+BASE = Path(os.environ.get('SOJU_BASE', str(Path.home() / '.battlenet-macos')))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 "@@ -129,7 +131,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, auth = None, None, False, False+ phase, shown, busy, auth, space = None, None, False, False, Nonetry:for line in process.stdout:if line.startswith('NEXUS_PROGRESS '):@@ -149,6 +151,10 @@ def stream(pid, choice, region, dest):elif line.strip():busy = busy or 'another download is using this folder' in lineauth = auth or 'Xbox authentication request failed' in line+ short = re.search(r'not enough free disk space.*?need (\d+) bytes, have (\d+) bytes', line)+ if short:+ space = max(0, int(short.group(1)) - int(short.group(2)))+ continue # reported below in words, without the folder pathprint(' ' + clean(line), flush=True)finally:# Stopping Soju's download also stops the backend; its checkpoint stays.@@ -161,6 +167,10 @@ 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 space is not None and code != 0:+ raise DownloadError('Not enough free space on ' + locations.volume_name(dest) + ': this game needs about ' ++ size(space) + ' more. Free up space or choose another download location in Accounts, '+ 'then download again to resume.')if auth and code != 0 and not has_xbox_profile():raise DownloadError(NO_XBOX_PROFILE)return code == 0 and phase == 'complete'@@ -199,18 +209,24 @@ def main():raise DownloadError('Set up Xbox PC in Platforms first (or run: soju xbox-install).')region = market()choice = choose(resolve(pid, region), pid)- dest = GAMES / pid+ dest = locations.destination(pid)dest.mkdir(parents=True, exist_ok=True)+ if not locations.inside(dest, dest.parent) or dest.is_symlink():+ raise DownloadError('The game folder is a link. Remove it and download again.')title = library_title(pid) or str(choice.get('title') or pid).strip()[:300]- print('Downloading ' + title + ' (' + str(choice.get('packageFormat')) + ') to ' + str(dest), flush=True)+ print('Downloading ' + title + ' (' + str(choice.get('packageFormat')) + ') to ' + locations.tilde(dest), flush=True)if not stream(pid, choice, region, dest):raise DownloadError('The download did not finish. Download again to resume it.')record = dict(schema=1, product_id=pid, content_id=choice['contentId'], title=title,installed_at=datetime.datetime.now(datetime.timezone.utc).isoformat())(dest / MARKER).write_text(json.dumps(record, ensure_ascii=False) + '\n')+ try:+ locations.remember(pid, dest, title)+ except OSError:+ pass # the next library scan records it; the download itself is completeprint(title + ' is downloaded. Press Play in Soju to start it.')return 0- except (DownloadError, OSError) as error:+ except (DownloadError, locations.LocationError, OSError) as error:print('soju: ' + str(error), file=sys.stderr)return 1except KeyboardInterrupt:diff --git a/scripts/xbox-run.py b/scripts/xbox-run.pyindex a569f4a4958..d2f553b5c7b 100755--- a/scripts/xbox-run.py+++ b/scripts/xbox-run.py@@ -31,10 +31,12 @@ import threadingimport timeimport xml.etree.ElementTree as ET+sys.path.insert(0, str(Path(__file__).resolve().parent))+import xbox_locations as locations # noqa: E402+ROOT = Path(__file__).resolve().parents[1]BASE = Path(os.environ.get('SOJU_BASE', str(Path.home() / '.battlenet-macos')))CLI = Path(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')@@ -296,10 +298,12 @@ def main():signal.signal(signal.SIGINT, interrupt)try:pid = product_id(sys.argv[1])- folder = GAMES / pid- record = folder / '.soju-xbox-install.json'- if not record.is_file():+ folder, kind = locations.locate(pid)+ if kind == 'missing':+ raise LaunchError(locations.not_connected(folder))+ if kind != 'complete':raise LaunchError('This game is not downloaded. Download it in Soju first.')+ record = folder / '.soju-xbox-install.json'if not (folder / '.xodus-streaming.msixvc').is_file():raise LaunchError('The game download is incomplete. Download it again to repair it.')lock = (folder / '.soju-xbox-run.lock').open('w')diff --git a/scripts/xbox.sh b/scripts/xbox.shindex a6073eb141d..48f2f656055 100755--- a/scripts/xbox.sh+++ b/scripts/xbox.sh@@ -1,6 +1,7 @@#!/usr/bin/env bash# Xbox PC / Microsoft Store through the Xodus backend: sign-in, downloads and play.# xbox.sh install | prepare | login | logout [--device] | status | download <ProductId> | run <ProductId> | kill+# | location [<folder>|--default]set -euo pipefailROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"BASE="${SOJU_BASE:-$HOME/.battlenet-macos}"@@ -42,7 +43,13 @@ case "${1:-}" infifiecho "Xbox PC is ready. Sign in from Soju > Accounts (or: soju xbox-login)."- echo "Downloads go to $XBOX_HOME/drive_c/XboxGames." ;;+ python3 "$ROOT/scripts/xbox_locations.py" show | head -1 ;;+ location)+ case "${2:-}" in+ '') exec python3 "$ROOT/scripts/xbox_locations.py" show ;;+ --default) exec python3 "$ROOT/scripts/xbox_locations.py" default ;;+ *) exec python3 "$ROOT/scripts/xbox_locations.py" set "$2" ;;+ esac ;;prepare)exec python3 "$ROOT/scripts/xbox-prefix.py" ;;run)@@ -112,5 +119,5 @@ print("Signed in" if json.load(sys.stdin).get("stored") else "Not signed in")' ;esacdone[ "$stopped" = 1 ] || echo "No Xbox download or game is running." ;;- *) echo "Usage: xbox.sh install|prepare|login|logout [--device]|status|download <ProductId>|run <ProductId>|kill" >&2; exit 64 ;;+ *) echo "Usage: xbox.sh install|prepare|login|logout [--device]|status|download <ProductId>|run <ProductId>|kill|location [<folder>|--default]" >&2; exit 64 ;;esacdiff --git a/scripts/xbox_locations.py b/scripts/xbox_locations.pynew file mode 100644index 00000000000..e313db2114f--- /dev/null+++ b/scripts/xbox_locations.py@@ -0,0 +1,450 @@+#!/usr/bin/env python3+"""Where Xbox PC games are downloaded: the Mac (default) or a folder on an external drive.++State lives in $SOJU_BASE/xbox-locations.json (0600):+ current the folder new downloads go to (null: the default folder in the Xbox prefix)+ roots every folder ever chosen, each with the id of its .soju-xbox-root.json, so a+ renamed volume (or "T7 1" next to another "T7") is found again by that id+ games product ID -> the root its download is in, so a game on an unplugged drive is+ still listed (as not connected) instead of looking "not downloaded"+APFS, Mac OS Extended (HFS+) and exFAT volumes are accepted (a game downloaded to an exFAT+SSD and started from it). FAT cannot hold the multi-GB package file, macOS mounts NTFS read-only,+and network volumes are too slow for the library scan.+Paths are only passed as argv, never through a shell.++usage: xbox_locations.py set <folder> | default | show | json+"""+import datetime+import json+import os+from pathlib import Path+import re+import shutil+import subprocess+import sys+import uuid++BASE = Path(os.environ.get('SOJU_BASE', str(Path.home() / '.battlenet-macos')))+DEFAULT = BASE / 'xbox-bottle/drive_c/XboxGames'+STATE = BASE / 'xbox-locations.json'+VOLUMES = Path('/Volumes')+SENTINEL = '.soju-xbox-root.json'+MARKER = '.soju-xbox-install.json'+CHECKPOINT = '.nexus-streaming-v1.jsonl'+FILESYSTEMS = ('apfs', 'hfs', 'exfat')+MIN_FREE = 1 << 30+PRODUCT = re.compile(r'[A-Z0-9]{12}')+FORMAT_HINT = ('Choose a folder on an APFS, Mac OS Extended or exFAT drive. To use this drive, '+ 'format it as APFS or exFAT in Disk Utility (this erases it).')+++class LocationError(Exception):+ pass+++def tilde(path):+ """Paths in messages and logs without the user name."""+ text, home = str(path), str(Path.home())+ return '~' + text[len(home):] if text == home or text.startswith(home + '/') else text+++def empty():+ return {'schema': 1, 'current': None, 'current_id': '', 'roots': [], 'games': {}}+++def load():+ try:+ state = json.loads(STATE.read_text())+ except (OSError, ValueError):+ return empty()+ if not isinstance(state, dict) or state.get('schema') != 1:+ return empty()+ clean = empty()+ if isinstance(state.get('current'), str) and os.path.isabs(state['current']):+ clean['current'] = state['current']+ clean['current_id'] = str(state.get('current_id') or '')[:64]+ for entry in state.get('roots') or []:+ if isinstance(entry, dict) and isinstance(entry.get('path'), str) and os.path.isabs(entry['path']):+ clean['roots'].append({'path': entry['path'], 'id': str(entry.get('id') or '')[:64]})+ for pid, game in (state.get('games') or {}).items():+ if PRODUCT.fullmatch(str(pid)) and isinstance(game, dict) and isinstance(game.get('root'), str):+ clean['games'][pid] = {'root': game['root'], 'root_id': str(game.get('root_id') or '')[:64],+ 'title': str(game.get('title') or pid)[:300],+ 'seen_at': str(game.get('seen_at') or '')[:40]}+ return clean+++def save(state):+ STATE.parent.mkdir(parents=True, exist_ok=True)+ temp = STATE.with_name(STATE.name + '.' + str(os.getpid()) + '.tmp')+ fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ with os.fdopen(fd, 'w') as stream:+ json.dump(state, stream, ensure_ascii=False, indent=1)+ stream.write('\n')+ os.replace(temp, STATE)+++def mounts():+ """(mount point, filesystem, options) for every mounted volume."""+ try:+ output = subprocess.run(['/sbin/mount'], capture_output=True, text=True, timeout=10).stdout+ except (OSError, subprocess.SubprocessError):+ return []+ found = []+ for line in output.splitlines():+ match = re.match(r'^.+? on (/.*) \(([^,)]+)(?:, ([^)]*))?\)$', line)+ if match:+ found.append((match.group(1), match.group(2).strip(), [o.strip() for o in (match.group(3) or '').split(',')]))+ return found+++def fs_type(path):+ """Filesystem of the volume holding path (longest matching mount point), or ''."""+ path = os.path.realpath(path)+ best = ('', '')+ for point, kind, _ in mounts():+ if (path == point or path.startswith(point.rstrip('/') + '/')) and len(point) >= len(best[0]):+ best = (point, kind)+ return best[1]+++def volume_name(path):+ parts = Path(path).parts+ return parts[2] if len(parts) > 2 and parts[1] == 'Volumes' else 'this Mac'+++def is_default(path):+ return os.path.realpath(path) == os.path.realpath(DEFAULT)+++def inside(path, root):+ path, root = os.path.realpath(path), os.path.realpath(root)+ return path == root or path.startswith(root.rstrip('/') + '/')+++def allowed(path):+ """A folder on a drive in /Volumes, in the home folder, or Soju's own folder; never a system folder."""+ real = Path(os.path.realpath(path))+ home = os.path.realpath(Path.home())+ on_drive = len(real.parts) >= 4 and real.parts[1] == 'Volumes'+ return on_drive or (inside(real, home) and str(real) != home) or inside(real, BASE)+++def check_root(raw):+ """The folder new downloads would use for a user's choice, or LocationError."""+ if not isinstance(raw, str) or not raw or '\x00' in raw or not os.path.isabs(raw):+ raise LocationError('Choose a folder with its full path (for example /Volumes/T7/XboxGames).')+ if '..' in Path(raw).parts:+ raise LocationError('Choose the folder itself, without "..".')+ path = Path(os.path.realpath(raw))+ if not path.is_dir():+ raise LocationError('That folder does not exist: ' + tilde(raw))+ parts = path.parts+ if len(parts) == 3 and parts[1] == 'Volumes':+ path = path / 'XboxGames' # a drive's top level: keep games in their own folder+ if not allowed(path):+ raise LocationError('Choose a folder on an external drive (in /Volumes) or in your home folder.')+ kind = fs_type(path if path.exists() else path.parent)+ if kind not in FILESYSTEMS:+ named = {'msdos': 'FAT', 'ntfs': 'NTFS'}.get(kind, kind or 'an unknown format')+ raise LocationError(volume_name(path) + ' uses ' + named + '. ' + FORMAT_HINT)+ return path+++def writable(folder):+ probe = folder / ('.soju-write-test-' + uuid.uuid4().hex)+ try:+ probe.write_bytes(b'')+ probe.unlink()+ except OSError:+ raise LocationError('Soju cannot write to ' + tilde(folder) + '. Check the drive is not read-only.') from None+++def root_id(root):+ try:+ value = json.loads((Path(root) / SENTINEL).read_text())+ return str(value.get('id') or '')[:64] if isinstance(value, dict) else ''+ except (OSError, ValueError):+ return ''+++def ensure_sentinel(root):+ existing = root_id(root)+ if existing:+ return existing+ ident = uuid.uuid4().hex+ (Path(root) / SENTINEL).write_text(json.dumps({'schema': 1, 'id': ident}) + '\n')+ try:+ os.chmod(Path(root) / SENTINEL, 0o600)+ except OSError:+ pass # drives with "ignore ownership"+ return ident+++def set_current(raw):+ path = check_root(raw)+ try:+ path.mkdir(exist_ok=True)+ except OSError:+ raise LocationError('Soju cannot create ' + tilde(path) + '. Check the drive is not read-only.') from None+ if not inside(path, path.parent): # created as a link by someone else meanwhile+ raise LocationError('That folder is a link. Choose a real folder.')+ writable(path)+ state = load()+ if is_default(path):+ state['current'], state['current_id'] = None, ''+ else:+ ident = ensure_sentinel(path)+ state['current'], state['current_id'] = str(path), ident+ # Roots are told apart by their id, never by path: another drive with the same+ # name keeps its own entry (and its games stay listed as not connected).+ state['roots'] = [r for r in state['roots'] if r['id'] != ident and (r['id'] or r['path'] != str(path))]+ state['roots'].append({'path': str(path), 'id': ident})+ save(state)+ return path+++def use_default():+ state = load()+ state['current'], state['current_id'] = None, ''+ save(state)+++def relocate(state, entry, warnings):+ """A root's current path: as saved, or found again by its id on a renamed volume."""+ path = entry['path']+ if Path(path).is_dir() and (not entry['id'] or root_id(path) == entry['id']):+ return path+ try:+ relative = Path(path).relative_to(VOLUMES)+ except ValueError:+ return None+ if not entry['id'] or not relative.parts:+ return None+ rest = Path(*relative.parts[1:])+ # Only mounted local volumes Soju can use: no network shares (a stale one can hang an open),+ # no NTFS, and not the "Macintosh HD" link to the startup disk.+ volumes = sorted(Path(point) for point, kind, _ in mounts()+ if kind in FILESYSTEMS and Path(point).parent == VOLUMES)+ for volume in volumes:+ candidate = volume / rest+ if str(candidate) != path and root_id(candidate) == entry['id'] and inside(candidate, volume):+ old, new = path, str(candidate)+ entry['path'] = new+ if state['current_id'] == entry['id'] or (not state['current_id'] and state['current'] == old):+ state['current'] = new+ for game in state['games'].values():+ if game.get('root_id') == entry['id'] or (not game.get('root_id') and game['root'] == old):+ game['root'] = new+ warnings.append('Xbox games on ' + volume_name(old) + ' are now found on ' + volume_name(new) + '.')+ return new+ return None+++def roots(state=None, warnings=None):+ """[(path or None when not connected, saved path, root id)], the current location first, the Mac last."""+ state = load() if state is None else state+ warnings = [] if warnings is None else warnings+ found, seen = [], set()+ entries = sorted(state['roots'], key=lambda r: not (r['id'] == state['current_id'] or r['path'] == state['current']))+ for entry in entries:+ saved = entry['path']+ path = relocate(state, entry, warnings)+ if path and path not in seen:+ seen.add(path)+ found.append((path, path, entry['id']))+ elif not path:+ found.append((None, saved, entry['id']))+ if str(DEFAULT) not in seen:+ found.append((str(DEFAULT), str(DEFAULT), ''))+ return found+++def folder_state(folder):+ if (folder / MARKER).is_file():+ return 'complete'+ if (folder / CHECKPOINT).is_file():+ return 'partial'+ return None+++def scan(state=None, warnings=None):+ """{pid: (folder, 'complete'|'partial')} on connected roots, plus {pid: (saved root, 'missing')}+ for indexed games whose drive is not connected. Updates the index (written only if it changed)."""+ state = load() if state is None else state+ warnings = [] if warnings is None else warnings+ before = json.dumps(state, sort_keys=True)+ games = {}+ listed_paths, listed_ids, ids = set(), set(), {}+ for path, saved, ident in roots(state, warnings):+ if path is None:+ continue+ root = Path(path)+ try:+ folders = sorted(p for p in root.iterdir() if PRODUCT.fullmatch(p.name))+ except OSError:+ if not is_default(root):+ warnings.append('Xbox games on ' + volume_name(path) + ' could not be read. Reconnect the drive and refresh.')+ continue+ # Only a root that was actually listed may drop games that are no longer on it.+ listed_paths.add(path)+ ids[path] = ident+ if ident:+ listed_ids.add(ident)+ for folder in folders:+ # A game folder must be a real folder inside its root (no links out of it).+ if folder.is_symlink() or not folder.is_dir() or not inside(folder, root):+ continue+ kind = folder_state(folder)+ if not kind:+ continue+ pid = folder.name+ if pid in games:+ if games[pid][1] == 'complete' or kind != 'complete':+ warnings.append('Xbox game ' + pid + ' is in two download folders; using ' ++ tilde(games[pid][0]) + '.')+ continue+ games[pid] = (folder, kind)+ now = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds')+ for pid, (folder, kind) in games.items():+ root = str(folder.parent)+ if is_default(root):+ state['games'].pop(pid, None)+ continue+ game = state['games'].get(pid) or {'title': pid}+ if kind == 'complete' and game.get('title', pid) == pid:+ try:+ game['title'] = str(json.loads((folder / MARKER).read_text()).get('title') or pid)[:300]+ except (OSError, ValueError, AttributeError):+ pass+ if game.get('root') != root or game.get('root_id') != ids.get(root, ''):+ game.update(root=root, root_id=ids.get(root, ''), seen_at=now)+ state['games'][pid] = game+ for pid, game in list(state['games'].items()):+ if pid in games:+ continue+ gone = game['root_id'] in listed_ids if game.get('root_id') else game['root'] in listed_paths+ if gone:+ del state['games'][pid] # its drive is here but the folder is gone: deleted+ else:+ games[pid] = (Path(game['root']), 'missing')+ if json.dumps(state, sort_keys=True) != before:+ try:+ save(state)+ except OSError:+ pass+ return games+++def remember(pid, folder, title):+ """Record a finished download so it stays listed while its drive is unplugged."""+ state = load()+ if is_default(folder.parent):+ state['games'].pop(pid, None)+ else:+ state['games'][pid] = {'root': str(folder.parent), 'root_id': root_id(folder.parent), 'title': str(title)[:300],+ 'seen_at': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds')}+ save(state)+++def not_connected(root):+ return ('The drive with this game (' + volume_name(root) + ') is not connected. '+ 'Connect it, then refresh the library.')+++def locate(pid):+ """(folder, 'complete'|'partial'|'missing'|None) for a product ID."""+ found = scan().get(pid)+ return found if found else (None, None)+++def current_root(state=None):+ state = load() if state is None else state+ return state['current'] or str(DEFAULT)+++def destination(pid):+ """The folder a download of pid goes to: an existing (partial) one, else the current location."""+ folder, kind = locate(pid)+ if kind == 'missing':+ raise LocationError(not_connected(folder))+ if folder is not None:+ return folder+ state = load()+ root = Path(current_root(state))+ if not is_default(root):+ if not allowed(root):+ raise LocationError('The saved download location is not allowed. Choose it again in Accounts.')+ roots(state, []) # finds a renamed drive by its id+ root = Path(current_root(state))+ if not root.is_dir() or (state['current_id'] and root_id(root) != state['current_id']):+ raise LocationError('The download location on ' + volume_name(root) + ' is not connected. '+ 'Connect the drive, or choose another location in Accounts.')+ kind = fs_type(root)+ if kind not in FILESYSTEMS:+ raise LocationError(volume_name(root) + ' cannot hold Xbox games. ' + FORMAT_HINT)+ else:+ root.mkdir(parents=True, exist_ok=True)+ try:+ if shutil.disk_usage(root).free < MIN_FREE:+ raise LocationError('There is less than 1 GB free on ' + volume_name(root) ++ '. Free up space or choose another download location in Accounts.')+ except OSError:+ pass+ folder = root / pid+ if folder.is_symlink() or (folder.exists() and not inside(folder, root)):+ raise LocationError('The game folder in ' + tilde(root) + ' is a link. Remove it and download again.')+ return folder+++def describe(state=None):+ state = load() if state is None else state+ root = current_root(state)+ info = {'path': tilde(root), 'volume': volume_name(root), 'default': is_default(root),+ 'available': Path(root).is_dir() or is_default(root), 'free_bytes': None}+ try:+ info['free_bytes'] = shutil.disk_usage(root if Path(root).is_dir() else BASE).free+ except OSError:+ pass+ return info+++def main(argv):+ action = argv[1] if len(argv) > 1 else 'show'+ try:+ if action == 'set' and len(argv) == 3:+ path = set_current(argv[2])+ print('New Xbox downloads go to ' + tilde(path) + ' (' + volume_name(path) + ').')+ print('Games already downloaded stay where they are.')+ elif action == 'default' and len(argv) == 2:+ use_default()+ print('New Xbox downloads go to this Mac (' + tilde(DEFAULT) + ').')+ elif action == 'show' and len(argv) == 2:+ warnings = []+ info = describe()+ print('Download location: ' + info['path'] + ('' if info['available'] else ' (not connected)'))+ for path, saved, _ in roots(load(), warnings):+ if path is None:+ print(' not connected: ' + volume_name(saved) + ' (' + tilde(saved) + ')')+ for line in warnings:+ print(line)+ elif action == 'json' and len(argv) == 2:+ warnings = []+ state = load()+ games = scan(state, warnings)+ listed = [{'path': tilde(saved), 'volume': volume_name(saved), 'connected': path is not None,+ 'partial': sum(1 for f, k in games.values() if k == 'partial' and str(f.parent) == path)}+ for path, saved, _ in roots(state, [])]+ print(json.dumps({'current': describe(state), 'roots': listed, 'warnings': warnings}, ensure_ascii=False))+ else:+ print(__doc__.strip().splitlines()[-1], file=sys.stderr)+ return 64+ return 0+ except (LocationError, OSError) as error:+ print('soju: ' + tilde(str(error)) if isinstance(error, LocationError) else+ 'soju: ' + str(error).replace(str(Path.home()), '~'), file=sys.stderr)+ return 1+++if __name__ == '__main__':+ sys.exit(main(sys.argv))diff --git a/tests/test_installation.py b/tests/test_installation.pyindex 34b5d5d35e9..ed2c6838e41 100644--- a/tests/test_installation.py+++ b/tests/test_installation.py@@ -329,13 +329,13 @@ class DownloadCheckTests(unittest.TestCase):{"tag_name": "engine-v9", "prerelease": False, "assets": [{"name": "wine-engine-x86_64.tar.xz", "digest": "sha256:" + d}]},{"tag_name": "v2.0.0", "prerelease": True, "assets": [{"name": "Soju-2.0.0-macos-arm64.zip", "digest": "sha256:" + d}]},{"tag_name": "v1.9.0", "prerelease": False, "assets": [{"name": "Soju-1.9.0-macos-arm64.zip", "digest": None}]},- {"tag_name": "v1.8.2", "prerelease": False, "assets": [- {"name": "Soju-1.8.2-macos-arm64.zip.sha256", "digest": "sha256:" + "b" * 64},- {"name": "Soju-1.8.2-macos-arm64.zip", "digest": "sha256:" + d}]},+ {"tag_name": "v1.9.0", "prerelease": False, "assets": [+ {"name": "Soju-1.9.0-macos-arm64.zip.sha256", "digest": "sha256:" + "b" * 64},+ {"name": "Soju-1.9.0-macos-arm64.zip", "digest": "sha256:" + d}]},])self.assertEqual(result.returncode, 0, result.stderr)- self.assertEqual(result.stdout.split(), ["v1.8.2",- "https://github.com/BCD1210/soju/releases/download/v1.8.2/Soju-1.8.2-macos-arm64.zip", d])+ self.assertEqual(result.stdout.split(), ["v1.9.0",+ "https://github.com/BCD1210/soju/releases/download/v1.9.0/Soju-1.9.0-macos-arm64.zip", d])def test_latest_release_fails_without_a_checked_zip(self):result = self.latest([{"tag_name": "v1.0.0", "prerelease": False, "assets": []}])diff --git a/tests/test_library.py b/tests/test_library.pyindex b22ee701929..4d2eee42d90 100644--- a/tests/test_library.py+++ b/tests/test_library.py@@ -176,7 +176,9 @@ class LibraryTests(unittest.TestCase):self.assertIn('drive is unavailable', result['warnings'][0])def test_no_installations_is_valid_empty_library(self):- self.assertEqual(self.lib.scan(), {'accounts': [], 'games': [], 'warnings': []})+ result = self.lib.scan()+ self.assertTrue(result.pop('xbox_location')['default'])+ self.assertEqual(result, {'accounts': [], 'games': [], 'warnings': []})if __name__ == '__main__': unittest.main()diff --git a/tests/test_xbox.py b/tests/test_xbox.pyindex 72165c906b2..ea27a3b93ba 100644--- a/tests/test_xbox.py+++ b/tests/test_xbox.py@@ -265,6 +265,236 @@ class XboxLibraryTests(unittest.TestCase):self.lib.command('xbox:' + SILKSONG, install=True)+class XboxLocationTests(unittest.TestCase):+ """Downloads on external drives: scripts/xbox_locations.py and its callers."""+ def setUp(self):+ import xbox_locations+ self.locs = xbox_locations+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.base = Path(self.temp.name).resolve() / 'base'+ self.games = self.base / 'xbox-bottle/drive_c/XboxGames'+ marker = self.base / 'xbox-bottle/drive_c' / library.CLIENTS['xbox']+ marker.parent.mkdir(parents=True)+ marker.write_text('{}')+ self.lib = library.Library(self.base)+ for name, value in (('BASE', self.base), ('DEFAULT', self.games), ('STATE', self.base / 'xbox-locations.json')):+ patcher = patch.object(self.locs, name, value)+ patcher.start()+ self.addCleanup(patcher.stop)+ self.ext = self.base / 'drive/XboxGames'+ self.ext.mkdir(parents=True)+ fs = patch.object(self.locs, 'fs_type', return_value='apfs')+ self.fs = fs.start()+ self.addCleanup(fs.stop)++ def finished(self, root, uid=SILKSONG, title='Silksong'):+ folder = root / uid+ folder.mkdir(parents=True, exist_ok=True)+ (folder / '.soju-xbox-install.json').write_text(json.dumps(dict(schema=1, product_id=uid, title=title)))+ return folder++ def scan(self):+ return {g['id']: g for g in self.lib.scan()['games']}++ def test_location_must_be_a_real_folder_outside_system_folders(self):+ link = self.base / 'to-etc'+ link.symlink_to('/etc')+ for bad in ('', 'relative/folder', str(self.ext) + '/../x', '/', '/Volumes', '/System/Library', '/usr', str(link),+ str(self.base / 'missing'), 'a\x00b'):+ with self.subTest(bad=bad), self.assertRaises(self.locs.LocationError):+ self.locs.set_current(bad)+ self.assertFalse(self.locs.STATE.exists())+ self.assertEqual(self.locs.set_current(str(self.ext)), self.ext)+ state = json.loads(self.locs.STATE.read_text())+ self.assertEqual(state['current'], str(self.ext))+ self.assertEqual(self.locs.STATE.stat().st_mode & 0o777, 0o600)+ self.assertTrue((self.ext / '.soju-xbox-root.json').is_file())++ def test_unsupported_filesystems_are_refused(self):+ for kind in ('msdos', 'ntfs', 'smbfs', 'nfs', ''):+ self.fs.return_value = kind+ with self.subTest(kind=kind), self.assertRaisesRegex(self.locs.LocationError, 'APFS'):+ self.locs.set_current(str(self.ext))+ for kind in ('hfs', 'exfat'):+ self.fs.return_value = kind+ self.locs.set_current(str(self.ext))++ def test_external_game_is_listed_played_and_downloaded_there(self):+ self.locs.set_current(str(self.ext))+ folder = self.finished(self.ext)+ wine = self.base / 'cx26-engine/bin/wine'+ wine.parent.mkdir(parents=True)+ wine.write_text('#!/bin/sh\n')+ wine.chmod(0o755)+ (self.base / 'cx26-engine/lib/external').mkdir(parents=True)+ (self.base / 'cx26-engine/lib/external/libd3dshared.dylib').write_text('')+ game = self.scan()['xbox:' + SILKSONG]+ self.assertEqual(game['install_path'], str(folder))+ self.assertTrue(game['downloaded'] and game['available'])+ self.assertEqual(self.lib.command('xbox:' + SILKSONG)[-2:], ['run', SILKSONG])+ self.assertEqual(self.locs.locate(SILKSONG), (folder, 'complete'))+ self.assertEqual(self.locs.destination(VOID), self.ext / VOID)+ self.assertEqual(self.lib.scan()['xbox_location']['default'], False)++ def test_partial_download_resumes_in_its_own_folder_after_location_change(self):+ partial = self.games / SILKSONG+ partial.mkdir(parents=True)+ (partial / '.nexus-streaming-v1.jsonl').write_text('{}\n')+ self.locs.set_current(str(self.ext))+ self.assertEqual(self.locs.destination(SILKSONG), partial)+ self.assertFalse((self.ext / SILKSONG).exists())++ def test_unplugged_drive_keeps_the_game_and_never_downloads_to_the_mac(self):+ self.locs.set_current(str(self.ext))+ self.finished(self.ext)+ svc.save_account(self.base, 'xbox', [dict(id='xbox:' + SILKSONG, platform='xbox', title='Silksong', format='MSIXVC')], 'Xbox')+ self.scan()+ unplugged = self.base / 'unplugged'+ self.ext.rename(unplugged)+ game = self.scan()['xbox:' + SILKSONG]+ self.assertEqual((game['downloaded'], game['available']), (True, False))+ self.assertIn('not connected', game['issue'])+ for install in (True, False):+ with self.assertRaisesRegex(ValueError, 'not connected'):+ self.lib.command('xbox:' + SILKSONG, install=install)+ with self.assertRaisesRegex(self.locs.LocationError, 'not connected'):+ self.locs.destination(SILKSONG)+ with self.assertRaisesRegex(self.locs.LocationError, 'not connected'):+ self.locs.destination(VOID)+ self.assertFalse((self.games / SILKSONG).exists())+ self.assertIn(SILKSONG, json.loads(self.locs.STATE.read_text())['games'])+ unplugged.rename(self.ext)+ self.assertTrue(self.scan()['xbox:' + SILKSONG]['available'])++ def test_deleted_game_on_a_connected_drive_is_forgotten(self):+ self.locs.set_current(str(self.ext))+ folder = self.finished(self.ext)+ self.scan()+ (folder / '.soju-xbox-install.json').unlink()+ folder.rmdir()+ self.assertNotIn('xbox:' + SILKSONG, self.scan())+ self.assertNotIn(SILKSONG, json.loads(self.locs.STATE.read_text())['games'])++ def test_renamed_volume_is_found_by_its_id(self):+ volumes = self.base / 'Volumes'+ drive = volumes / 'T7' / 'XboxGames'+ drive.mkdir(parents=True)+ mounted = [(str(volumes / 'T7 1'), 'apfs', []), (str(volumes / 'Share'), 'smbfs', [])]+ with patch.object(self.locs, 'VOLUMES', volumes), patch.object(self.locs, 'mounts', return_value=mounted):+ self.locs.set_current(str(drive))+ self.finished(drive)+ self.scan()+ (volumes / 'T7').rename(volumes / 'T7 1')+ result = self.lib.scan()+ game = {g['id']: g for g in result['games']}['xbox:' + SILKSONG]+ self.assertTrue(game['available'])+ self.assertEqual(game['install_path'], str(volumes / 'T7 1/XboxGames' / SILKSONG))+ self.assertEqual(json.loads(self.locs.STATE.read_text())['current'], str(volumes / 'T7 1/XboxGames'))++ def test_another_drive_with_the_same_name_is_not_used(self):+ self.locs.set_current(str(self.ext))+ (self.ext / '.soju-xbox-root.json').write_text(json.dumps({'schema': 1, 'id': 'someone-else'}))+ with self.assertRaisesRegex(self.locs.LocationError, 'not connected'):+ self.locs.destination(SILKSONG)++ def test_a_second_drive_with_the_same_path_keeps_the_first_drives_games(self):+ self.locs.set_current(str(self.ext))+ self.finished(self.ext)+ self.scan()+ first = self.base / 'drive-a'+ self.ext.parent.rename(first) # drive A unplugged+ self.ext.mkdir(parents=True) # drive B mounts at the same path+ self.locs.set_current(str(self.ext))+ game = self.scan()['xbox:' + SILKSONG]+ self.assertEqual((game['downloaded'], game['available']), (True, False))+ with self.assertRaisesRegex(ValueError, 'not connected'):+ self.lib.command('xbox:' + SILKSONG, install=True)+ self.assertFalse((self.ext / SILKSONG).exists())+ self.assertEqual(len(json.loads(self.locs.STATE.read_text())['roots']), 2)++ def test_an_unreadable_drive_does_not_forget_its_games(self):+ self.locs.set_current(str(self.ext))+ self.finished(self.ext)+ self.scan()+ real = Path.iterdir+ def broken(path):+ if Path(path) == self.ext:+ raise OSError('I/O error')+ return real(path)+ with patch.object(Path, 'iterdir', broken):+ result = self.lib.scan()+ self.assertTrue(any('could not be read' in w for w in result['warnings']))+ self.assertIn(SILKSONG, json.loads(self.locs.STATE.read_text())['games'])++ def test_game_in_two_folders_uses_the_finished_one(self):+ self.locs.set_current(str(self.ext))+ partial = self.games / SILKSONG+ partial.mkdir(parents=True)+ (partial / '.nexus-streaming-v1.jsonl').write_text('{}\n')+ done = self.finished(self.ext)+ self.assertEqual(self.locs.locate(SILKSONG), (done, 'complete'))++ def test_links_out_of_a_download_folder_are_ignored(self):+ self.locs.set_current(str(self.ext))+ outside = self.finished(self.base / 'elsewhere')+ (self.ext / VOID).symlink_to(outside)+ self.assertEqual(self.locs.locate(VOID), (None, None))+ with self.assertRaisesRegex(self.locs.LocationError, 'link'):+ self.locs.destination(VOID)++ def fake_download(self, streaming):+ cli = self.base / 'xodus-cli'+ plan = json.dumps(dict(schema=1, status='ready', choices=[XboxDownloadTests.CHOICE]))+ cli.write_text('#!/bin/sh\n[ "$1" = resolve-package ] && { printf "%s\\n" ' + repr(plan) + '; exit 0; }\n'+ '[ "$1" = streaming ] || exit 9\n' + streaming)+ cli.chmod(0o755)+ env = dict(os.environ, SOJU_BASE=str(self.base), SOJU_XODUS_BIN=str(cli))+ return subprocess.run([sys.executable, str(ROOT / 'scripts/xbox-download.py'), SILKSONG],+ env=env, capture_output=True, text=True, timeout=30)++ def test_download_goes_to_the_chosen_drive_and_is_remembered(self):+ self.locs.set_current(str(self.ext))+ done = "printf '%s\\n' " + repr('NEXUS_PROGRESS ' + json.dumps(dict(schema=1, phase='complete'))) + '\n'+ result = self.fake_download(done)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertTrue((self.ext / SILKSONG / '.soju-xbox-install.json').is_file())+ self.assertFalse((self.games / SILKSONG).exists())+ self.assertEqual(json.loads(self.locs.STATE.read_text())['games'][SILKSONG]['root'], str(self.ext))++ def test_out_of_space_is_reported_in_words(self):+ line = 'echo "Error: not enough free disk space on /Volumes/T7/x: need 5000000000 bytes, have 1000000000 bytes"; exit 1\n'+ result = self.fake_download(line)+ self.assertEqual(result.returncode, 1)+ self.assertIn('Not enough free space', result.stderr)+ self.assertIn('4.0 GB', result.stderr)+ self.assertNotIn('/Volumes/T7/x', result.stdout + result.stderr)++ def test_tampered_saved_location_is_refused(self):+ self.locs.save({'schema': 1, 'current': '/usr', 'roots': [{'path': '/usr', 'id': ''}], 'games': {}})+ with self.assertRaisesRegex(self.locs.LocationError, 'not allowed'):+ self.locs.destination(SILKSONG)++ def test_paths_in_messages_hide_the_user_name(self):+ self.assertEqual(self.locs.tilde(Path.home() / 'Games'), '~/Games')+ self.assertEqual(self.locs.tilde('/Volumes/T7/XboxGames'), '/Volumes/T7/XboxGames')++ def test_cli_sets_and_resets_the_location(self):+ env = dict(os.environ, SOJU_BASE=str(self.base))+ run = lambda *a: subprocess.run(['/bin/bash', str(ROOT / 'scripts/xbox.sh'), 'location', *a],+ env=env, capture_output=True, text=True, timeout=30)+ bad = run('/System')+ self.assertEqual(bad.returncode, 1)+ self.assertIn('external drive', bad.stderr)+ shown = run()+ self.assertEqual(shown.returncode, 0, shown.stderr)+ self.assertIn('Download location', shown.stdout)+ self.assertEqual(run('--default').returncode, 0)+ action = subprocess.run(['/bin/bash', str(ROOT / 'scripts/desktop-action.sh'), 'xbox', 'location', '/System'],+ env=env, capture_output=True, text=True, timeout=30)+ self.assertNotEqual(action.returncode, 0)++class XboxDownloadTests(unittest.TestCase):CHOICE = dict(contentId='807c7d6a-409f-48be-8190-30b09baf7cd4', kind='Game', packageFormat='MSIXVC',platform='Windows.Desktop', productId=SILKSONG, supported=True, title='Silksong')@@ -418,7 +648,7 @@ class XboxInstallerPlanTests(unittest.TestCase):def test_cli_lists_xbox_commands(self):result = subprocess.run(['/bin/bash', str(ROOT / 'scripts/soju'), '--help'], capture_output=True, text=True)- for command in ('xbox-install', 'xbox-login', 'xbox-sync', 'xbox-download', 'xbox-logout'):+ for command in ('xbox-install', 'xbox-login', 'xbox-sync', 'xbox-download', 'xbox-logout', 'xbox-location'):self.assertIn(command, result.stdout)bad = subprocess.run(['/bin/bash', str(ROOT / 'scripts/soju'), 'xbox-sync', 'XX'], capture_output=True, text=True)self.assertEqual(bad.returncode, 64)@@ -720,6 +950,7 @@ class XboxStopAndSignOutTests(unittest.TestCase):root = Path(temp) / 'repo'(root / 'scripts').mkdir(parents=True)(root / 'scripts/xbox-run.py').write_text((ROOT / 'scripts/xbox-run.py').read_text())+ (root / 'scripts/xbox_locations.py').write_text((ROOT / 'scripts/xbox_locations.py').read_text())# Stand-in for xbox-prefix.py: a long download running in a child process.(root / 'scripts/xbox-prefix.py').write_text('import subprocess, sys\n'