mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 20:36:04 +00:00
Add experimental Xbox and PC Game Pass store support (#1156)
This commit is contained in:
1 parent
8e02904a04
commit
a63f3b1fbc
56 files changed
+3720
-47
No files matched your search
@@ -20,6 +20,10 @@ class App : Application() {
|
||||
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName()
|
||||
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
|
||||
.runningAppProcesses?.firstOrNull { it.pid == android.os.Process.myPid() }?.processName
|
||||
if (process == "$packageName:xboxlogin") {
|
||||
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xbox")
|
||||
return
|
||||
}
|
||||
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
|
||||
CrashHandler.install(this)
|
||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||
@@ -36,5 +40,6 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,7 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
|
||||
"usr/local/bin/droiddeck-steam-shim" to "usr/local/bin/droiddeck-steam-shim",
|
||||
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
|
||||
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
|
||||
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
|
||||
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
|
||||
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
|
||||
@@ -133,7 +134,9 @@ object SessionFiles {
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
) + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
|
||||
) + listOf("xodus-cli", "xodus-service", "LICENSE.xodus", "LICENSE.nexus", "LICENSE.LGPL-2.1", "LICENSE.nghttp2", "backend.lock.json", "runtime.lock.json", "version",
|
||||
"windows/xgameruntime.dll", "windows/winhttp.dll", "windows/windows.web.dll", "windows/twinapi.appcore.dll", "windows/libnghttp2.dll")
|
||||
.map { "usr/local/lib/droiddeck-xbox/$it" to "usr/local/lib/droiddeck-xbox/$it" } + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ object CloudSaves {
|
||||
val item = sidecar.extra["catalogItemId"].orEmpty()
|
||||
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
|
||||
}
|
||||
Store.AMAZON, Store.ITCH -> ""
|
||||
Store.AMAZON, Store.ITCH, Store.XBOX -> ""
|
||||
} ?: return null
|
||||
p.edit().putString("cloud_template_$id", fetched).apply()
|
||||
Log.i(TAG, "cloud ${store.id} $id template ${if (fetched.isEmpty()) "none" else "found"}")
|
||||
@@ -96,7 +96,7 @@ object CloudSaves {
|
||||
val dir = when (store) {
|
||||
Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
|
||||
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
|
||||
Store.AMAZON, Store.ITCH -> null
|
||||
Store.AMAZON, Store.ITCH, Store.XBOX -> null
|
||||
}
|
||||
return dir to (if (dir == null) "unresolved" else "ok")
|
||||
}
|
||||
@@ -121,7 +121,7 @@ object CloudSaves {
|
||||
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
|
||||
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
|
||||
}
|
||||
Store.AMAZON, Store.ITCH -> null
|
||||
Store.AMAZON, Store.ITCH, Store.XBOX -> null
|
||||
}
|
||||
|
||||
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
|
||||
|
||||
@@ -12,7 +12,7 @@ internal object LoginFlows {
|
||||
Store.GOG -> GogFlow(state)
|
||||
Store.EPIC -> epicFlow()
|
||||
Store.AMAZON -> amazonFlow()
|
||||
Store.ITCH -> null
|
||||
Store.ITCH, Store.XBOX -> null
|
||||
}
|
||||
|
||||
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
|
||||
|
||||
@@ -4,6 +4,7 @@ enum class Store(val id: String, val label: String, val shortLabel: String) {
|
||||
GOG("gog", "GOG", "GOG"),
|
||||
EPIC("epic", "Epic Games", "Epic"),
|
||||
AMAZON("amazon", "Amazon Games", "Amazon"),
|
||||
XBOX("xbox", "Xbox", "Xbox"),
|
||||
ITCH("itch", "itch.io", "itch");
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -67,7 +67,10 @@ object StoreAccounts {
|
||||
fun write(context: Context, store: Store, json: JSONObject) {
|
||||
unavailable.remove(store)
|
||||
val f = credentialsFile(context, store)
|
||||
if (seal(f, json) == null) put(f, json.toString())
|
||||
if (seal(f, json, retry = store == Store.XBOX) == null) {
|
||||
check(store != Store.XBOX) { "Android Keystore is unavailable for Xbox credentials" }
|
||||
put(f, json.toString())
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
@@ -86,18 +89,19 @@ object StoreAccounts {
|
||||
|
||||
fun signedInAs(context: Context, store: Store): String? {
|
||||
val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null
|
||||
if (store == Store.XBOX) return json.optString("username").takeIf { it.isNotBlank() }
|
||||
if (json.optString("access_token", "").isEmpty()) return null
|
||||
return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label }
|
||||
}
|
||||
|
||||
private fun seal(f: File, json: JSONObject): File? {
|
||||
if (keystoreFailed) return null
|
||||
private fun seal(f: File, json: JSONObject, retry: Boolean = false): File? {
|
||||
if (keystoreFailed && !retry) return null
|
||||
val text = json.toString()
|
||||
val envelope = try {
|
||||
CredentialCipher.seal(text, keys).also { check(CredentialCipher.open(it, keys) == text) { "check failed" } }
|
||||
} catch (e: Exception) {
|
||||
keystoreFailed = true
|
||||
Log.w(TAG, "stores: keystore unavailable, credentials stay plain (${e.javaClass.simpleName})")
|
||||
Log.w(TAG, "stores: keystore unavailable (${e.javaClass.simpleName})")
|
||||
return null
|
||||
}
|
||||
put(f, envelope.toString())
|
||||
|
||||
@@ -21,7 +21,9 @@ data class CatalogItem(
|
||||
val sizeBytes: Long = 0L,
|
||||
val extra: Map<String, String> = emptyMap(),
|
||||
val mature: Boolean = false,
|
||||
val subscription: Boolean = false,
|
||||
) {
|
||||
val accessible: Boolean get() = owned || subscription
|
||||
val isDiscounted: Boolean get() = discountPercent > 0 && originalPrice.isNotBlank()
|
||||
val key: String get() = "${store.id}:$id"
|
||||
}
|
||||
@@ -49,7 +51,9 @@ fun installedCards(store: Store, installed: List<InstalledStoreGame>, library: L
|
||||
return installed.filter { it.sidecar.store == store }.map { game ->
|
||||
val s = game.sidecar
|
||||
byId[s.id] ?: byTitle[s.title.lowercase()]
|
||||
?: CatalogItem(store, s.id, s.title, imageUrl = s.hero ?: s.cover, tallImageUrl = s.cover ?: s.hero, owned = true)
|
||||
?: CatalogItem(store, s.id, s.title, imageUrl = s.hero ?: s.cover, tallImageUrl = s.cover ?: s.hero,
|
||||
owned = s.store != Store.XBOX || s.extra["access"] == "owned",
|
||||
subscription = s.store == Store.XBOX && s.extra["access"] == "gamepass")
|
||||
}.distinctBy { it.id }.sortedBy { it.title.lowercase() }
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.stores
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import java.io.File
|
||||
|
||||
@@ -63,6 +64,14 @@ object StoreLaunch {
|
||||
private const val CODE_VAR = "DD_X"
|
||||
private const val CLIENT_VAR = "DD_A"
|
||||
|
||||
fun installedGame(context: Context, store: Store, id: String): Library.SteamGame? {
|
||||
val folder = StoreInstallRoot.gameFolders(context).firstOrNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.let { it.store == store && it.id == id && it.isInstalled } == true
|
||||
} ?: return null
|
||||
val game = AddedGames.single(context, folder.path) ?: return null
|
||||
return Library.addedGame(context, game)
|
||||
}
|
||||
|
||||
fun refreshLauncher(folder: File, sidecar: StoreGameSidecar) {
|
||||
if (sidecar.launcher != LAUNCHER) return
|
||||
val file = File(folder, LAUNCHER)
|
||||
|
||||
@@ -37,6 +37,7 @@ object StoreLaunchRequests {
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
Thread({ com.droiddeck.launcher.stores.xbox.XboxRuntime.stop() }, "xbox-service-stop").start()
|
||||
synchronized(lock) {
|
||||
observer?.stopWatching()
|
||||
observer = null
|
||||
@@ -50,6 +51,12 @@ object StoreLaunchRequests {
|
||||
return
|
||||
}
|
||||
val reply = when (request.optString("op")) {
|
||||
"xbox-released" -> {
|
||||
com.droiddeck.launcher.stores.xbox.XboxRuntime.released(request.optString("id"))
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
"xbox-prepare" -> runCatching { com.droiddeck.launcher.stores.xbox.XboxRuntime.prepare(app, request.getString("id")) }
|
||||
.getOrElse { JSONObject().put("ok", false).put("reason", "Xbox account service is unavailable. Sign in again and retry.") }
|
||||
"gog-achievements" -> runCatching { com.droiddeck.launcher.stores.gog.GogComet.prepare(app, request.optString("id")) }
|
||||
.getOrElse { JSONObject().put("ok", false).put("ready", false).put("reason", "service-unavailable") }
|
||||
"epic-code" -> {
|
||||
|
||||
@@ -31,7 +31,7 @@ object StoreSizes {
|
||||
private fun cache(context: Context, store: Store) = caches.getOrPut(store) { SizeCache.forStore(context.applicationContext.filesDir, store) }
|
||||
|
||||
fun request(context: Context, item: CatalogItem) {
|
||||
if (!item.owned || item.sizeBytes > 0 || item.store == Store.GOG || known.containsKey(item.key)) return
|
||||
if (!item.accessible || item.sizeBytes > 0 || item.store == Store.GOG || known.containsKey(item.key)) return
|
||||
resolve(context, item).thenAccept { bytes ->
|
||||
if (bytes != null) StoresState.post { known[item.key] = bytes }
|
||||
}
|
||||
@@ -39,7 +39,7 @@ object StoreSizes {
|
||||
|
||||
fun resolve(context: Context, item: CatalogItem): CompletableFuture<Long?> {
|
||||
val available = known[item.key] ?: item.sizeBytes.takeIf { it > 0 }
|
||||
if (!item.owned || item.store == Store.GOG || item.sizeBytes > 0) return CompletableFuture.completedFuture(available)
|
||||
if (!item.accessible || item.store == Store.GOG || item.sizeBytes > 0) return CompletableFuture.completedFuture(available)
|
||||
if (available != null) return CompletableFuture.completedFuture(available)
|
||||
val app = context.applicationContext
|
||||
val version = item.extra["version"].orEmpty()
|
||||
@@ -55,7 +55,7 @@ object StoreSizes {
|
||||
Store.EPIC -> EpicPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||
Store.ITCH -> {}
|
||||
Store.GOG -> {}
|
||||
Store.GOG, Store.XBOX -> {}
|
||||
}
|
||||
}
|
||||
}, pool).exceptionally { error ->
|
||||
@@ -108,7 +108,7 @@ object StoreSizes {
|
||||
val bytes = AmazonApiClient.getBytes(AmazonApiClient.appendPath(spec.downloadUrl, "manifest.proto"), token) ?: return 0L
|
||||
AmazonManifest.parse(bytes).totalInstallSize
|
||||
}
|
||||
Store.GOG -> 0L
|
||||
Store.GOG, Store.XBOX -> 0L
|
||||
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
|
||||
} }
|
||||
}
|
||||
@@ -20,6 +20,8 @@ object StoresState {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
val accounts = mutableStateMapOf<Store, String>()
|
||||
var accountsLoaded by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
val library = mutableStateMapOf<Store, List<CatalogItem>>()
|
||||
|
||||
@@ -84,11 +86,15 @@ object StoresState {
|
||||
val partial = StoreInstallRoot.unfinished(app)
|
||||
val version = if (StoresNative.available) StoresNative.version ?: "" else ""
|
||||
main.post {
|
||||
accounts.clear()
|
||||
found.forEach { (store, name) -> accounts[store] = name }
|
||||
installed = onDisk
|
||||
unfinished = partial
|
||||
engine = version
|
||||
androidx.compose.runtime.snapshots.Snapshot.withMutableSnapshot {
|
||||
val restored = found.toMap()
|
||||
accounts.keys.toList().filter { it !in restored }.forEach { accounts.remove(it) }
|
||||
accounts.putAll(restored)
|
||||
installed = onDisk
|
||||
unfinished = partial
|
||||
engine = version
|
||||
accountsLoaded = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ object SavedQueue {
|
||||
put("store", i.store.id); put("id", i.id); put("title", i.title)
|
||||
put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: "")
|
||||
put("tags", i.tags); put("developer", i.developer); put("description", i.description)
|
||||
put("size", i.sizeBytes); put("owned", i.owned)
|
||||
put("size", i.sizeBytes); put("owned", i.owned); put("subscription", i.subscription)
|
||||
put("extra", JSONObject(i.extra))
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ object SavedQueue {
|
||||
id = o.getString("id"), title = o.getString("title"),
|
||||
imageUrl = o.optString("image").ifEmpty { null }, tallImageUrl = o.optString("tall").ifEmpty { null },
|
||||
tags = o.optString("tags"), developer = o.optString("developer"), description = o.optString("description"),
|
||||
owned = o.optBoolean("owned", true), sizeBytes = o.optLong("size"),
|
||||
owned = o.optBoolean("owned", true), subscription = o.optBoolean("subscription"), sizeBytes = o.optLong("size"),
|
||||
extra = extra?.keys()?.asSequence()?.associateWith { extra.getString(it) } ?: emptyMap(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.stores.*
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import java.io.File
|
||||
|
||||
object XboxBackend : StoreBackend {
|
||||
override val store = Store.XBOX
|
||||
@Volatile private var access: Map<String, String> = emptyMap()
|
||||
@Volatile private var generation = 0
|
||||
private var syncing: Int? = null
|
||||
|
||||
override fun signIn(context: Context) {
|
||||
context.startActivity(Intent(context, XboxLoginActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
|
||||
@Synchronized override fun signOut(context: Context) {
|
||||
generation++
|
||||
XboxCredentials.invalidate(context)
|
||||
XboxLibraryCache.clear(context)
|
||||
XboxRuntime.stop()
|
||||
access = emptyMap()
|
||||
StoresState.post { packageChoice = null; StoresState.shelves.remove(store); StoresState.found.remove(store) }
|
||||
}
|
||||
|
||||
@Synchronized override fun syncLibrary(context: Context, force: Boolean) {
|
||||
val app = context.applicationContext
|
||||
val current = generation
|
||||
if (syncing == current) return
|
||||
syncing = current
|
||||
Thread({
|
||||
try {
|
||||
val account = StoreAccounts.signedInAs(app, store) ?: error("Sign in to Xbox first.")
|
||||
val market = Xodus.market()
|
||||
val cached = XboxLibraryCache.read(app, account, market)
|
||||
synchronized(this) {
|
||||
if (current != generation) return@Thread
|
||||
if (cached != null) access = cached.games.associate { it.id to it.extra.getValue("access") }
|
||||
}
|
||||
StoresState.post {
|
||||
if (current == generation) {
|
||||
if (cached != null) StoresState.library[store] = mergeItems(StoresState.library[store], cached.games)
|
||||
StoresState.problems.remove(store)
|
||||
if (cached == null || force) StoresState.status[store] = "Syncing Xbox library…"
|
||||
else StoresState.status.remove(store)
|
||||
}
|
||||
}
|
||||
if (cached != null && !cached.needsRefresh(force)) return@Thread
|
||||
val licenses = XboxCatalog.access(Xodus.run(app, listOf("library", "--json", "--market", market)), account, market)
|
||||
val games = XboxCatalog.products(licenses.keys.toList(), licenses, market).sortedBy { it.title.lowercase() }
|
||||
synchronized(this) {
|
||||
if (current != generation || StoreAccounts.signedInAs(app, store) != account) return@Thread
|
||||
access = licenses
|
||||
runCatching { XboxLibraryCache.write(app, account, market, games) }
|
||||
.onFailure { StoresState.logLine("Xbox: library cache could not be saved") }
|
||||
}
|
||||
StoresState.post {
|
||||
if (current == generation) {
|
||||
StoresState.library[store] = mergeItems(StoresState.library[store], games)
|
||||
StoresState.status.remove(store)
|
||||
StoresState.problems.remove(store)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
StoresState.post {
|
||||
if (current == generation) {
|
||||
StoresState.status.remove(store)
|
||||
StoresState.problems[store] = e.message ?: "Xbox library could not be loaded."
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
synchronized(this) { if (syncing == current) syncing = null }
|
||||
}
|
||||
}, "xbox-library").start()
|
||||
}
|
||||
|
||||
override fun loadShelves(context: Context, force: Boolean) {
|
||||
val current = generation
|
||||
Thread({
|
||||
runCatching { XboxCatalog.featured(access) }.onSuccess { games ->
|
||||
if (current == generation) StoresState.post { StoresState.shelves[store] = StoreShelves(trending = games) }
|
||||
}.onFailure { if (current == generation) StoresState.post { StoresState.problems[store] = "Microsoft Store could not be reached. Try again." } }
|
||||
}, "xbox-store").start()
|
||||
}
|
||||
|
||||
override fun search(context: Context, query: String): List<CatalogItem> = XboxCatalog.search(query, access)
|
||||
|
||||
class PackageChoice(val item: CatalogItem, val root: File, val choices: List<org.json.JSONObject>)
|
||||
var packageChoice by androidx.compose.runtime.mutableStateOf<PackageChoice?>(null)
|
||||
private set
|
||||
|
||||
fun dismissPackages() { packageChoice = null }
|
||||
fun selectPackage(context: Context, choice: org.json.JSONObject) {
|
||||
val pending = packageChoice ?: return
|
||||
packageChoice = null
|
||||
val item = pending.item.copy(extra = pending.item.extra + ("contentId" to choice.getString("contentId")))
|
||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(context, item, pending.root)
|
||||
enqueue(context.applicationContext, item, pending.root)
|
||||
}
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: File) {
|
||||
val app = context.applicationContext
|
||||
if (!item.extra["baseId"].isNullOrBlank()) { XboxContent.install(app, item); return }
|
||||
if (!item.extra["contentId"].isNullOrBlank()) { enqueue(app, item, root); return }
|
||||
Thread({
|
||||
try {
|
||||
val plan = Xodus.run(app, listOf("resolve-package", item.id, "--json", "--market", item.extra["market"] ?: Xodus.market()))
|
||||
require(plan.getInt("schema") == 1 && plan.getString("rootProductId") == item.id)
|
||||
val choices = XboxCatalog.objects(plan.getJSONArray("choices")).filter { it.optBoolean("supported") && it.optString("kind") == "Game" }
|
||||
check(choices.isNotEmpty()) { "This offer has no supported PC package." }
|
||||
if (plan.getString("status") == "ready" && choices.size == 1) {
|
||||
val selected = item.copy(extra = item.extra + ("contentId" to choices.single().getString("contentId")))
|
||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, selected, root)
|
||||
enqueue(app, selected, root)
|
||||
} else StoresState.post { packageChoice = PackageChoice(item, root, choices) }
|
||||
} catch (e: Exception) {
|
||||
DownloadQueue.recordFailed(app, DownloadEntry(store, item.id, item.title), e.message ?: "Xbox package could not be resolved.") { install(app, item, root) }
|
||||
}
|
||||
}, "xbox-package").start()
|
||||
}
|
||||
|
||||
fun update(context: Context, game: InstalledStoreGame) {
|
||||
check(!XboxRuntime.isActive(game.sidecar.id)) { "Close this Xbox game before updating it." }
|
||||
val sidecar = game.sidecar
|
||||
val item = CatalogItem(store, sidecar.id, sidecar.title, sidecar.hero, tallImageUrl = sidecar.cover,
|
||||
owned = sidecar.extra["access"] == "owned", subscription = sidecar.extra["access"] == "gamepass", extra = sidecar.extra)
|
||||
val root = game.folder.parentFile!!.parentFile!!
|
||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(context, item, root)
|
||||
enqueue(context, item, root)
|
||||
}
|
||||
|
||||
private fun enqueue(context: Context, item: CatalogItem, root: File) {
|
||||
val app = context.applicationContext
|
||||
val folder = StoreInstallRoot.folderFor(app, store, item.id, item.title, root)
|
||||
val entry = DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes,
|
||||
location = StoreInstallRoot.labelFor(app, folder))
|
||||
DownloadQueue.enqueue(app, entry) { XboxInstaller(app, item, folder) }
|
||||
}
|
||||
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) {}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.time.Instant
|
||||
|
||||
internal object XboxCatalog {
|
||||
private val productId = Regex("[A-Z0-9]{12}")
|
||||
private val plans = setOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC0K6L8", "CFQ7TTC10QFD")
|
||||
|
||||
fun access(json: JSONObject, account: String, market: String, now: Instant = Instant.now()): Map<String, String> {
|
||||
require(json.getInt("schema") == 1 && json.getString("account") == account && json.getString("market") == market)
|
||||
val age = java.time.Duration.between(timestamp(json.getString("checkedAt")), now).seconds
|
||||
require(age in -60..299)
|
||||
val array = json.getJSONArray("entitlements")
|
||||
require(array.length() <= 10_000)
|
||||
val rows = LinkedHashMap<String, JSONObject>()
|
||||
val blocked = HashSet<String>()
|
||||
for (i in 0 until array.length()) {
|
||||
val row = array.optJSONObject(i) ?: continue
|
||||
val id = row.optString("productId")
|
||||
if (!productId.matches(id)) continue
|
||||
val valid = row.opt("status") is String && row.opt("isTrial") is Boolean && row.opt("special") is Boolean &&
|
||||
row.opt("sharingSource") is String && runCatching { timestamp(row.getString("endDate")) }.isSuccess &&
|
||||
(row.isNull("satisfiedByProductId") || productId.matches(row.optString("satisfiedByProductId")))
|
||||
if (!valid || id in rows || id in blocked) { blocked.add(id); rows.remove(id) } else rows[id] = row
|
||||
}
|
||||
fun kind(id: String, visited: Set<String> = emptySet()): String? {
|
||||
if (id in blocked || id in visited || visited.size >= 16) return null
|
||||
val row = rows[id] ?: return null
|
||||
if (row.getString("status") != "Active" || row.getBoolean("isTrial") || row.getBoolean("special") ||
|
||||
row.getString("sharingSource") != "None" || !timestamp(row.getString("endDate")).isAfter(now)) return null
|
||||
val parent = row.optString("satisfiedByProductId").takeUnless { it.isBlank() || it == "null" }
|
||||
if (parent == null) return if (id in plans) null else "owned"
|
||||
if (parent in blocked) return null
|
||||
if (parent in plans) return "gamepass"
|
||||
return kind(parent, visited + id)
|
||||
}
|
||||
return rows.keys.mapNotNull { id -> kind(id)?.let { id to it } }.toMap()
|
||||
}
|
||||
|
||||
private fun timestamp(value: String): Instant = java.time.OffsetDateTime.parse(value).toInstant()
|
||||
|
||||
fun products(ids: List<String>, access: Map<String, String> = emptyMap(), market: String = Xodus.market()): List<CatalogItem> {
|
||||
return rawProducts(ids, market).mapNotNull { product(it, access) }
|
||||
}
|
||||
|
||||
fun rawProducts(ids: List<String>, market: String = Xodus.market()): List<JSONObject> {
|
||||
return ids.map { it.uppercase() }.filter { productId.matches(it) }.distinct().chunked(25).flatMap { batch ->
|
||||
val body = get("https://displaycatalog.mp.microsoft.com/v7.0/products?bigIds=${batch.joinToString(",")}&market=$market&languages=en-us,neutral")
|
||||
objects(body.optJSONArray("Products")).filter { it.optString("ProductId").uppercase() in batch }
|
||||
}
|
||||
}
|
||||
|
||||
fun search(query: String, access: Map<String, String>): List<CatalogItem> {
|
||||
if (productId.matches(query.uppercase())) return products(listOf(query.uppercase()), access)
|
||||
if (query.length !in 2..100) return emptyList()
|
||||
val q = java.net.URLEncoder.encode(query, "UTF-8")
|
||||
val body = get("https://apps.microsoft.com/api/products/search?query=$q&mediaType=games&age=all&price=all&category=all&subscription=all&gl=${Xodus.market()}&hl=en-us")
|
||||
val ids = objects(body.optJSONArray("productsList")).map { it.optString("productId") }.take(60)
|
||||
return products(ids, access)
|
||||
}
|
||||
|
||||
fun featured(access: Map<String, String>): List<CatalogItem> {
|
||||
val body = get("https://apps.microsoft.com/api/Reco/GetComputedProductsList?listName=TopTrending&pgNo=1&noItems=12&filteredCategories=AllProducts&mediaType=Games&gl=${Xodus.market()}&hl=en-us&exp=0")
|
||||
return products(objects(body.optJSONArray("productsList")).map { it.optString("productId") }.take(24), access)
|
||||
}
|
||||
|
||||
internal fun product(json: JSONObject, access: Map<String, String>): CatalogItem? {
|
||||
val id = json.optString("ProductId").uppercase()
|
||||
if (!productId.matches(id) || json.optString("ProductType") != "Game") return null
|
||||
val localized = objects(json.optJSONArray("LocalizedProperties")).firstOrNull() ?: return null
|
||||
val title = localized.optString("ProductTitle").takeIf { it.isNotBlank() } ?: return null
|
||||
val packages = objects(json.optJSONArray("DisplaySkuAvailabilities")).flatMap {
|
||||
objects(it.optJSONObject("Sku")?.optJSONObject("Properties")?.optJSONArray("Packages"))
|
||||
}
|
||||
val pc = packages.filter { pkg -> objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } }
|
||||
if (pc.none { it.optString("PackageFormat").equals("MSIXVC", true) }) return null
|
||||
val images = objects(localized.optJSONArray("Images"))
|
||||
fun image(vararg kinds: String): String? = kinds.firstNotNullOfOrNull { purpose ->
|
||||
images.firstOrNull { it.optString("ImagePurpose") == purpose }?.optString("Uri")?.let { raw ->
|
||||
val url = if (raw.startsWith("//")) "https:$raw" else raw
|
||||
runCatching { java.net.URI(url) }.getOrNull()?.takeIf {
|
||||
it.scheme == "https" && it.host in setOf("store-images.s-microsoft.com", "store-images.microsoft.com") && it.userInfo == null && it.port == -1
|
||||
}?.toString()
|
||||
}
|
||||
}
|
||||
val kind = access[id]
|
||||
return CatalogItem(Store.XBOX, id, title, image("SuperHeroArt", "Hero", "BoxArt"),
|
||||
tallImageUrl = image("TitledPoster", "Poster", "BoxArt"),
|
||||
owned = kind == "owned", subscription = kind == "gamepass",
|
||||
storeUrl = "https://www.xbox.com/games/store/$id",
|
||||
publisher = localized.optString("PublisherName"), developer = localized.optString("DeveloperName"),
|
||||
description = localized.optString("ProductDescription"),
|
||||
sizeBytes = pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L,
|
||||
extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty()),
|
||||
)
|
||||
}
|
||||
|
||||
fun objects(array: JSONArray?): List<JSONObject> = if (array == null) emptyList() else
|
||||
(0 until array.length()).mapNotNull { array.optJSONObject(it) }
|
||||
|
||||
private fun get(url: String): JSONObject = JSONObject(StoreNet.get(url) ?: error("Microsoft Store could not be reached. Try again."))
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.stores.*
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
internal object XboxContent {
|
||||
data class Offer(val item: CatalogItem, val installed: Boolean)
|
||||
data class Plan(val base: InstalledStoreGame, val offers: List<Offer>, val error: String? = null)
|
||||
var plan by mutableStateOf<Plan?>(null)
|
||||
private set
|
||||
fun dismiss() { plan = null }
|
||||
|
||||
fun manage(context: Context, base: InstalledStoreGame) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
try {
|
||||
val manifest = XboxManifest.read(base.folder)
|
||||
check(manifest.storeId.matches(Regex("[A-Z0-9]{12}"))) { "The package has no valid Store ID." }
|
||||
val account = StoreAccounts.signedInAs(app, Store.XBOX) ?: error("Sign in to Xbox first.")
|
||||
val market = base.sidecar.extra["market"] ?: Xodus.market()
|
||||
val licenses = XboxCatalog.access(Xodus.run(app, listOf("library", "--json", "--market", market)), account, market)
|
||||
val products = XboxCatalog.rawProducts(listOf(manifest.storeId) + manifest.related, market)
|
||||
val baseProduct = products.singleOrNull { it.optString("ProductId") == manifest.storeId }
|
||||
val families = packages(baseProduct).map { it.optString("PackageFamilyName") }.filter { it.startsWith(manifest.name + "_") }.toSet()
|
||||
val offers = products.filter { it.optString("ProductId") in manifest.related && it.optString("ProductType") == "Durable" }.mapNotNull { product ->
|
||||
val id = product.getString("ProductId")
|
||||
val access = licenses[id] ?: return@mapNotNull null
|
||||
val packages = packages(product).filter { it.optString("MainPackageFamilyNameForDlc") in families }
|
||||
.distinctBy { it.optString("ContentId") }
|
||||
if (packages.size != 1) return@mapNotNull null
|
||||
val pkg = packages.single()
|
||||
val cid = pkg.optString("ContentId")
|
||||
if (!cid.matches(Regex("[0-9a-fA-F-]{36}"))) return@mapNotNull null
|
||||
val localized = XboxCatalog.objects(product.optJSONArray("LocalizedProperties")).firstOrNull()
|
||||
val item = CatalogItem(Store.XBOX, id, localized?.optString("ProductTitle")?.ifBlank { id } ?: id,
|
||||
imageUrl = base.sidecar.cover, owned = access == "owned", subscription = access == "gamepass",
|
||||
sizeBytes = pkg.optLong("MaxDownloadSizeInBytes"),
|
||||
extra = mapOf("baseId" to base.sidecar.id, "contentId" to cid, "market" to market, "family" to pkg.getString("PackageFamilyName")))
|
||||
Offer(item, File(base.folder, ".xbox-content/$id/.droiddeck-content.json").isFile)
|
||||
}
|
||||
StoresState.post { plan = Plan(base, offers) }
|
||||
} catch (e: Exception) { StoresState.post { plan = Plan(base, emptyList(), e.message ?: "Xbox content could not be loaded.") } }
|
||||
}, "xbox-content").start()
|
||||
}
|
||||
|
||||
private fun packages(product: JSONObject?): List<JSONObject> = XboxCatalog.objects(product?.optJSONArray("DisplaySkuAvailabilities"))
|
||||
.filter { it.optJSONObject("Sku")?.optJSONObject("Properties")?.optBoolean("IsTrial", true) == false }
|
||||
.flatMap { XboxCatalog.objects(it.optJSONObject("Sku")?.optJSONObject("Properties")?.optJSONArray("Packages")) }
|
||||
.filter { pkg -> pkg.optString("PackageFormat") == "MSIXVC" &&
|
||||
XboxCatalog.objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } }
|
||||
|
||||
private val parents = java.util.concurrent.ConcurrentHashMap<String, String>()
|
||||
fun busy(base: String): Boolean = StoresState.latestDownloads.any { it.isActive && parents[it.id] == base }
|
||||
|
||||
fun install(context: Context, item: CatalogItem) {
|
||||
plan = null
|
||||
val base = runCatching { base(context, item) }.getOrElse { error ->
|
||||
StoresState.post { StoresState.problems[Store.XBOX] = error.message ?: "The base game is not available." }
|
||||
return
|
||||
}
|
||||
if (XboxRuntime.isActive(base.sidecar.id)) {
|
||||
StoresState.post { StoresState.problems[Store.XBOX] = "Close the Xbox game before changing its content." }
|
||||
return
|
||||
}
|
||||
parents[item.id] = base.sidecar.id
|
||||
val folder = File(base.folder, ".xbox-content/${item.id}")
|
||||
if (folder.canonicalPath != base.folder.canonicalPath + "/.xbox-content/${item.id}") {
|
||||
StoresState.post { StoresState.problems[Store.XBOX] = "The Xbox content folder contains a link outside this game." }
|
||||
return
|
||||
}
|
||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(context, item, base.folder.parentFile!!.parentFile!!)
|
||||
com.droiddeck.launcher.stores.download.DownloadQueue.enqueue(context,
|
||||
com.droiddeck.launcher.stores.download.DownloadEntry(Store.XBOX, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes)) {
|
||||
XboxInstaller(context.applicationContext, item, folder)
|
||||
}
|
||||
}
|
||||
|
||||
fun base(context: Context, item: CatalogItem): InstalledStoreGame {
|
||||
require(item.id.matches(Regex("[A-Z0-9]{12}")))
|
||||
val id = item.extra["baseId"] ?: error("Missing Xbox base game")
|
||||
val folder = StoreInstallRoot.gameFolders(context).firstOrNull { StoreGameSidecar.read(it)?.let { s -> s.store == Store.XBOX && s.id == id && s.isInstalled } == true }
|
||||
?: error("The Xbox base game is not installed.")
|
||||
return InstalledStoreGame(StoreGameSidecar.read(folder)!!, folder)
|
||||
}
|
||||
|
||||
fun complete(context: Context, item: CatalogItem, folder: File) {
|
||||
val base = base(context, item)
|
||||
val parent = XboxManifest.read(base.folder)
|
||||
val content = XboxManifest.read(folder)
|
||||
check(item.id in parent.related && content.storeId == item.id && content.dependency == parent.name && content.publisher == parent.publisher && item.extra["family"].orEmpty().startsWith(content.name + "_")) {
|
||||
"The downloaded content does not belong to this Xbox game."
|
||||
}
|
||||
require(folder.canonicalPath == base.folder.canonicalPath + "/.xbox-content/${item.id}")
|
||||
val marker = File(folder, ".droiddeck-content.json")
|
||||
val temporary = File(folder, marker.name + ".tmp")
|
||||
temporary.writeText(JSONObject().put("productId", item.id).put("parent", base.sidecar.id)
|
||||
.put("contentId", item.extra["contentId"]).put("version", content.version).toString())
|
||||
check(temporary.renameTo(marker))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import android.content.Context
|
||||
import android.net.LocalServerSocket
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreAccounts
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.Closeable
|
||||
import java.io.InputStream
|
||||
import java.util.UUID
|
||||
|
||||
internal class XboxCredentials(private val app: Context) : Closeable {
|
||||
val name = "droiddeck-xbox-${UUID.randomUUID()}"
|
||||
private val generation = storage(app) { epoch(app) }
|
||||
private val server = LocalServerSocket(name)
|
||||
@Volatile private var closed = false
|
||||
|
||||
init {
|
||||
Thread({
|
||||
while (!closed) {
|
||||
val socket = runCatching { server.accept() }.getOrNull() ?: break
|
||||
socket.use {
|
||||
it.soTimeout = 10_000
|
||||
val reply = runCatching {
|
||||
check(it.peerCredentials.uid == android.os.Process.myUid())
|
||||
storage(app) {
|
||||
check(epoch(app) == generation)
|
||||
answer(JSONObject(readLine(it.inputStream.buffered(), 2_097_152)))
|
||||
}
|
||||
}.getOrElse { JSONObject().put("ok", false) }
|
||||
runCatching { it.outputStream.write((reply.toString() + "\n").toByteArray()) }
|
||||
}
|
||||
}
|
||||
}, "xbox-credentials").start()
|
||||
}
|
||||
|
||||
private fun answer(request: JSONObject): JSONObject {
|
||||
val key = request.getString("key")
|
||||
require(key.isNotEmpty() && key.length <= 512)
|
||||
val record = StoreAccounts.read(app, Store.XBOX)
|
||||
check(!StoreAccounts.isUnavailable(Store.XBOX))
|
||||
val json = record ?: JSONObject()
|
||||
val slots = json.optJSONObject("slots") ?: JSONObject().also { json.put("slots", it) }
|
||||
val result = JSONObject().put("ok", true)
|
||||
when (request.getString("op")) {
|
||||
"get" -> result.put("value", slots.opt(key) ?: JSONObject.NULL)
|
||||
"set" -> {
|
||||
val bytes = request.getJSONArray("value")
|
||||
require(bytes.length() <= 262_144)
|
||||
for (i in 0 until bytes.length()) require(bytes.getInt(i) in 0..255)
|
||||
slots.put(key, bytes)
|
||||
StoreAccounts.write(app, Store.XBOX, json)
|
||||
}
|
||||
"remove" -> { slots.remove(key); StoreAccounts.write(app, Store.XBOX, json) }
|
||||
else -> error("Invalid credential operation")
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
override fun close() { closed = true; runCatching { server.close() } }
|
||||
|
||||
companion object {
|
||||
val lock = Any()
|
||||
private fun epoch(app: Context): String = runCatching { java.io.File(StoreAccounts.dir(app, Store.XBOX), "generation").readText() }.getOrDefault("")
|
||||
fun invalidate(app: Context) = storage(app) {
|
||||
java.io.File(StoreAccounts.dir(app, Store.XBOX), "generation").writeText(UUID.randomUUID().toString())
|
||||
StoreAccounts.clear(app, Store.XBOX)
|
||||
}
|
||||
fun <T> storage(app: Context, block: () -> T): T = synchronized(lock) {
|
||||
java.io.RandomAccessFile(java.io.File(StoreAccounts.dir(app, Store.XBOX), "account.lock"), "rw").use { file ->
|
||||
file.channel.lock().use { block() }
|
||||
}
|
||||
}
|
||||
fun readLine(input: InputStream, limit: Int): String {
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
while (out.size() <= limit) {
|
||||
val byte = input.read()
|
||||
if (byte == 10) return out.toString("UTF-8")
|
||||
if (byte < 0) throw java.io.EOFException("Xbox backend disconnected")
|
||||
out.write(byte)
|
||||
}
|
||||
error("Xbox backend response exceeded its limit")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.*
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal class XboxInstaller(private val app: Context, private val item: CatalogItem, private val folder: File) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
private val paused = CountDownLatch(1)
|
||||
@Volatile private var child: Xodus.Child? = null
|
||||
@Volatile private var delete = false
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
if (cancelled.get()) return null
|
||||
check(StoreAccounts.signedInAs(app, Store.XBOX) != null) { "Sign in to Xbox before installing." }
|
||||
val market = item.extra["market"]?.takeIf { it.matches(Regex("[A-Z]{2}")) } ?: Xodus.market()
|
||||
val selected = item.extra["contentId"].orEmpty()
|
||||
require(selected.matches(Regex("[a-fA-F0-9-]{36}"))) { "Select a PC game package before installing." }
|
||||
val content = !item.extra["baseId"].isNullOrBlank()
|
||||
if (content) {
|
||||
check(!XboxRuntime.isActive(item.extra["baseId"].orEmpty())) { "Close the base game before changing Xbox content." }
|
||||
check(item.id in XboxManifest.read(XboxContent.base(app, item).folder).related) { "This content is not related to the base game." }
|
||||
val base = XboxContent.base(app, item)
|
||||
require(folder.canonicalPath == base.folder.canonicalPath + "/.xbox-content/${item.id}")
|
||||
File(folder, ".droiddeck-content.json").delete()
|
||||
folder.mkdirs()
|
||||
} else {
|
||||
check(!XboxRuntime.isActive(item.id)) { "Close this Xbox game before updating it." }
|
||||
StoreInstalls.markUpdating(folder)
|
||||
StoreInstalls.begin(folder, Store.XBOX, item.id, item.title, item.tallImageUrl, item.imageUrl)
|
||||
}
|
||||
var complete = false
|
||||
var sequence = -1L
|
||||
try {
|
||||
val source = if (content) selected else item.id
|
||||
val selection = if (content) emptyList() else listOf("--selected-content-id", selected)
|
||||
Xodus.start(app, listOf("streaming", source, folder.path, "--market", market,
|
||||
"--progress-json", "--control-stdin") + selection).use { process ->
|
||||
child = process
|
||||
val diagnostics = Xodus.diagnostics(process)
|
||||
if (cancelled.get()) process.process.destroy()
|
||||
process.process.inputStream.bufferedReader().useLines { lines -> lines.forEach { line ->
|
||||
if (line.startsWith("NEXUS_PROGRESS ")) {
|
||||
val progress = JSONObject(line.removePrefix("NEXUS_PROGRESS "))
|
||||
require(progress.getInt("schema") == 1 && progress.getLong("sequence") > sequence)
|
||||
sequence = progress.getLong("sequence")
|
||||
if (progress.optBoolean("paused")) paused.countDown()
|
||||
when (progress.getString("phase")) {
|
||||
"complete" -> complete = true
|
||||
"downloading", "download", "transfer" -> handle.progress(progress.getLong("completedBytes"), progress.optLong("totalBytes"))
|
||||
"finalizing", "installing" -> handle.stage(DownloadStage.INSTALL)
|
||||
else -> handle.stage(DownloadStage.MANIFEST)
|
||||
}
|
||||
}
|
||||
} }
|
||||
check(process.process.waitFor(15, TimeUnit.SECONDS)) { "Xbox installer did not exit." }
|
||||
diagnostics.join(2000)
|
||||
if (cancelled.get()) return null
|
||||
check(process.process.exitValue() == 0 && complete) { "Xbox download did not complete. Resume to retry with fresh licenses." }
|
||||
}
|
||||
if (content) {
|
||||
XboxContent.complete(app, item, folder)
|
||||
return folder.path
|
||||
}
|
||||
val exe = executable(folder)
|
||||
StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe,
|
||||
installVersion = XboxManifest.read(folder).version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl,
|
||||
extra = item.extra + mapOf("contentId" to selected, "market" to market)))
|
||||
return folder.path
|
||||
} finally {
|
||||
child = null
|
||||
if (delete && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteTree(folder)
|
||||
else if (delete) StoreInstalls.discard(app, folder, emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
delete = deleteFiles
|
||||
val process = child
|
||||
if (process == null) {
|
||||
if (deleteFiles && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteTree(folder)
|
||||
else if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
|
||||
return
|
||||
}
|
||||
Thread({
|
||||
runCatching {
|
||||
process.send(JSONObject().put("schema", 1).put("command", "pause"))
|
||||
paused.await(3, TimeUnit.SECONDS)
|
||||
}
|
||||
process.close()
|
||||
}, "xbox-download-stop").start()
|
||||
}
|
||||
|
||||
companion object {
|
||||
internal fun executable(folder: File): String = XboxManifest.executable(folder)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
internal object XboxLibraryCache {
|
||||
data class Snapshot(val games: List<CatalogItem>, val savedAt: Long) {
|
||||
fun needsRefresh(force: Boolean, now: Long = System.currentTimeMillis()): Boolean =
|
||||
force || now - savedAt !in 0 until 15 * 60 * 1000L
|
||||
}
|
||||
|
||||
private fun prefs(app: Context) = app.getSharedPreferences("xbox", Context.MODE_PRIVATE)
|
||||
fun read(app: Context, account: String, market: String): Snapshot? =
|
||||
decode(prefs(app).getString("library", null), account, market)
|
||||
|
||||
fun write(app: Context, account: String, market: String, games: List<CatalogItem>) {
|
||||
check(prefs(app).edit().putString("library", encode(account, market, games)).commit())
|
||||
}
|
||||
|
||||
fun clear(app: Context) { prefs(app).edit().remove("library").commit() }
|
||||
|
||||
internal fun encode(account: String, market: String, games: List<CatalogItem>, now: Long = System.currentTimeMillis()): String =
|
||||
JSONObject().put("schema", 1).put("account", account).put("market", market).put("savedAt", now)
|
||||
.put("games", JSONArray().apply {
|
||||
for (game in games) put(JSONObject().put("id", game.id).put("title", game.title)
|
||||
.put("image", game.imageUrl).put("poster", game.tallImageUrl).put("description", game.description)
|
||||
.put("developer", game.developer).put("publisher", game.publisher).put("size", game.sizeBytes)
|
||||
.put("access", if (game.subscription) "gamepass" else if (game.owned) "owned" else "none"))
|
||||
}).toString()
|
||||
|
||||
internal fun decode(text: String?, account: String, market: String, now: Long = System.currentTimeMillis()): Snapshot? = runCatching {
|
||||
require(text != null && text.length <= 8_000_000)
|
||||
val json = JSONObject(text)
|
||||
require(json.getInt("schema") == 1 && json.getString("account") == account && json.getString("market") == market)
|
||||
val savedAt = json.getLong("savedAt")
|
||||
require(savedAt > 0 && savedAt <= now + 60_000)
|
||||
val rows = json.getJSONArray("games")
|
||||
require(rows.length() <= 10_000)
|
||||
val games = (0 until rows.length()).map { index ->
|
||||
val row = rows.getJSONObject(index)
|
||||
val id = row.getString("id")
|
||||
val title = row.getString("title")
|
||||
val access = row.getString("access")
|
||||
require(id.matches(Regex("[A-Z0-9]{12}")) && title.isNotBlank() && access in setOf("owned", "gamepass"))
|
||||
CatalogItem(Store.XBOX, id, title, row.optString("image").takeIf { it.isNotEmpty() },
|
||||
tallImageUrl = row.optString("poster").takeIf { it.isNotEmpty() },
|
||||
description = row.optString("description"), developer = row.optString("developer"), publisher = row.optString("publisher"),
|
||||
sizeBytes = row.optLong("size"), owned = access == "owned", subscription = access == "gamepass",
|
||||
storeUrl = "https://www.xbox.com/games/store/$id", extra = mapOf("market" to market, "access" to access))
|
||||
}
|
||||
require(games.map { it.id }.distinct().size == games.size)
|
||||
Snapshot(games, savedAt)
|
||||
}.getOrNull()
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Color
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.webkit.CookieManager
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import android.widget.Button
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreAccounts
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class XboxLoginActivity : ComponentActivity() {
|
||||
private lateinit var host: LinearLayout
|
||||
private lateinit var status: TextView
|
||||
private var view: WebView? = null
|
||||
@Volatile private var child: Xodus.Child? = null
|
||||
@Volatile private var session = 0L
|
||||
@Volatile private var closed = false
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
host = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setBackgroundColor(Color.BLACK) }
|
||||
status = TextView(this).apply { setTextColor(Color.WHITE); text = "Preparing Microsoft sign-in…"; setPadding(24, 16, 24, 16) }
|
||||
host.addView(status)
|
||||
host.addView(Button(this).apply { text = getString(com.droiddeck.launcher.R.string.stores_login_close); setOnClickListener { finish() } })
|
||||
setContentView(host)
|
||||
if (android.os.Build.VERSION.SDK_INT < 28 || !WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) ||
|
||||
!WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
|
||||
status.text = "Update Android System WebView to sign in to Xbox."
|
||||
return
|
||||
}
|
||||
CookieManager.getInstance().removeAllCookies { begin() }
|
||||
}
|
||||
|
||||
private fun begin() {
|
||||
if (closed) return
|
||||
Thread({
|
||||
if (closed) return@Thread
|
||||
try {
|
||||
Xodus.start(applicationContext, listOf("--external-webview-stdio", "login")).use { process ->
|
||||
child = process
|
||||
if (closed) return@use
|
||||
Xodus.diagnostics(process)
|
||||
val timer = Thread({
|
||||
runCatching { if (!process.process.waitFor(10, TimeUnit.MINUTES)) process.process.destroy() }
|
||||
}, "xbox-login-timeout").apply { start() }
|
||||
var ready = false
|
||||
var latest = 0L
|
||||
val input = process.process.inputStream.buffered()
|
||||
while (!closed) {
|
||||
val line = try { XboxCredentials.readLine(input, 131_072) } catch (e: java.io.EOFException) { break }
|
||||
if (!line.startsWith("NEXUS_AUTH_V1 ")) continue
|
||||
val frame = JSONObject(line.removePrefix("NEXUS_AUTH_V1 "))
|
||||
when (frame.getString("type")) {
|
||||
"ready" -> {
|
||||
check(!ready && frame.getInt("version") == 1)
|
||||
ready = true
|
||||
process.send(JSONObject().put("type", "hello").put("version", 1))
|
||||
}
|
||||
"open" -> {
|
||||
val next = frame.getLong("session")
|
||||
check(ready && next > latest && next <= 32 && trusted(frame.getString("url")))
|
||||
latest = next; session = next
|
||||
runOnUiThread { if (!closed) open(frame) }
|
||||
}
|
||||
"close" -> {
|
||||
check(frame.getLong("session") == session)
|
||||
session = 0L
|
||||
runOnUiThread { disposeView(); status.text = "Completing Microsoft sign-in…" }
|
||||
}
|
||||
"context" -> {
|
||||
check(frame.getLong("session") == session)
|
||||
val context = frame.getString("context")
|
||||
check(context.length <= 4096)
|
||||
val message = JSONObject().put("type", "callback").put("value", JSONObject()
|
||||
.put("name", "CloudExperienceHost.getContext")
|
||||
.put("args", org.json.JSONArray(listOf("CloudExperienceHost", "TokenBroker", "TokenBroker", "{\"PrivatePropertyBag\":1,\"PasswordlessConnect\":1,\"PreferAssociate\":1,\"ChromelessUI\":0}")))
|
||||
.put("context", context))
|
||||
val active = session
|
||||
runOnUiThread { if (active == session && trusted(view?.url.orEmpty())) view?.evaluateJavascript(
|
||||
"globalThis['CloudExperienceHost.Bridge.dispatchMessage'](${JSONObject.quote(message.toString())})", null) }
|
||||
}
|
||||
else -> error("Unsupported Xbox sign-in response")
|
||||
}
|
||||
}
|
||||
check(process.process.waitFor(5, TimeUnit.SECONDS) && process.process.exitValue() == 0 && ready && latest > 0 && session == 0L)
|
||||
timer.interrupt()
|
||||
}
|
||||
child = null
|
||||
if (closed) return@Thread
|
||||
val account = Xodus.run(applicationContext, listOf("account", "--json"))
|
||||
check(account.optBoolean("stored"))
|
||||
XboxCredentials.storage(this) {
|
||||
val record = StoreAccounts.read(this, Store.XBOX) ?: error("Xbox credentials missing")
|
||||
record.put("username", account.getString("username"))
|
||||
StoreAccounts.write(this, Store.XBOX, record)
|
||||
}
|
||||
runOnUiThread { finish() }
|
||||
} catch (e: Exception) {
|
||||
child = null
|
||||
if (!closed) runOnUiThread { disposeView(); status.text = "Microsoft sign-in did not complete. Close this window and try again." }
|
||||
}
|
||||
}, "xbox-login").start()
|
||||
}
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
private fun open(frame: JSONObject) {
|
||||
disposeView()
|
||||
val active = frame.getLong("session")
|
||||
val web = WebView(this)
|
||||
view = web
|
||||
web.settings.apply {
|
||||
javaScriptEnabled = true; domStorageEnabled = true
|
||||
allowFileAccess = false; allowContentAccess = false
|
||||
mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
userAgentString = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; MSAppHost/3.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.26100"
|
||||
}
|
||||
WebViewCompat.addWebMessageListener(web, "droiddeckXbox", origins) { _, message, origin, mainFrame, _ ->
|
||||
val payload = message.data
|
||||
if (mainFrame && trusted(origin.toString()) && trusted(web.url.orEmpty()) && active == session && payload != null && payload.toByteArray().size <= 65_536) {
|
||||
runCatching { child?.send(JSONObject().put("type", "ipc").put("session", active).put("payload", payload)) }
|
||||
}
|
||||
}
|
||||
WebViewCompat.addDocumentStartJavaScript(web,
|
||||
"if(window===window.top){Object.defineProperty(globalThis.external,'notify',{value:p=>{if(typeof p==='string')droiddeckXbox.postMessage(p)},configurable:false,writable:false})}", origins)
|
||||
web.webViewClient = object : WebViewClient() {
|
||||
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = !trusted(request.url.toString())
|
||||
override fun onPageFinished(view: WebView, url: String) {
|
||||
if (!trusted(url)) { finish(); return }
|
||||
status.text = "Microsoft sign-in"
|
||||
val uri = Uri.parse(url)
|
||||
if (uri.host == "login.live.com" && uri.path == "/ppsecure/post.srf") {
|
||||
view.evaluateJavascript("JSON.stringify(globalThis.ServerData ?? null)") { raw ->
|
||||
val payload = runCatching { org.json.JSONArray("[$raw]").getString(0) }.getOrNull()
|
||||
if (active == session && payload != null && payload != "null" && payload.length <= 65_536) runCatching {
|
||||
child?.send(JSONObject().put("type", "ipc").put("session", active).put("payload", payload))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
host.addView(web, LinearLayout.LayoutParams(-1, 0, 1f))
|
||||
val headers = frame.getJSONObject("headers")
|
||||
val values = headers.keys().asSequence().associateWith { key ->
|
||||
require(key in allowedHeaders)
|
||||
headers.getString(key).also { value -> require(value.length <= 4096 && value.all { it in ' '..'~' }) }
|
||||
}
|
||||
web.loadUrl(frame.getString("url"), values)
|
||||
}
|
||||
|
||||
private fun disposeView() { view?.let { host.removeView(it); it.stopLoading(); it.destroy() }; view = null }
|
||||
override fun onDestroy() {
|
||||
closed = true
|
||||
val current = child; child = null
|
||||
Thread({ runCatching { current?.close() } }, "xbox-login-close").start()
|
||||
disposeView()
|
||||
CookieManager.getInstance().removeAllCookies(null)
|
||||
android.webkit.WebStorage.getInstance().deleteAllData()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val hosts = setOf("login.live.com", "account.live.com", "login.microsoftonline.com", "login.microsoft.com", "account.microsoft.com", "sisu.xboxlive.com")
|
||||
private val origins = hosts.map { "https://$it" }.toSet()
|
||||
private val allowedHeaders = setOf("cxh-capabilities", "cxh-correlationid", "cxh-msabinaryversion", "cxh-identityclientbinaryversion", "cxh-osversioninfo", "cxh-platform", "cxh-protocol", "cxh-source", "hostapp")
|
||||
internal fun trusted(value: String): Boolean = runCatching {
|
||||
val url = java.net.URI(value)
|
||||
url.scheme == "https" && url.host in hosts && url.port == -1 && url.userInfo == null
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import java.io.File
|
||||
import org.xmlpull.v1.XmlPullParser
|
||||
|
||||
internal object XboxManifest {
|
||||
data class Info(val storeId: String, val name: String, val publisher: String, val version: String,
|
||||
val dependency: String, val related: List<String>, val executables: List<String>)
|
||||
|
||||
fun read(folder: File): Info {
|
||||
val manifests = folder.listFiles().orEmpty().filter { it.name.equals("MicrosoftGame.config", true) && it.isFile }
|
||||
require(manifests.size == 1) { "Missing or ambiguous MicrosoftGame.config." }
|
||||
val manifest = manifests.single()
|
||||
require(manifest.length() <= 1_048_576)
|
||||
val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) }
|
||||
val identities = ArrayList<List<String>>()
|
||||
val storeIds = ArrayList<String>()
|
||||
val dependencies = ArrayList<String>()
|
||||
val related = ArrayList<String>()
|
||||
val entries = ArrayList<String>()
|
||||
fun attribute(name: String) = parser.getAttributeValue(null, name).orEmpty()
|
||||
var root = false
|
||||
var elements = 0
|
||||
manifest.inputStream().use { input ->
|
||||
parser.setInput(input, null)
|
||||
while (true) {
|
||||
when (parser.nextToken()) {
|
||||
XmlPullParser.END_DOCUMENT -> break
|
||||
XmlPullParser.DOCDECL -> error("Xbox game manifests cannot contain a DTD.")
|
||||
XmlPullParser.START_TAG -> {
|
||||
require(++elements <= 10_000 && parser.depth <= 64) { "Xbox game manifest is too complex." }
|
||||
if (parser.depth == 1) { require(!root && parser.name == "Game"); root = true }
|
||||
when (parser.name) {
|
||||
"Identity" -> identities.add(listOf(attribute("Name"), attribute("Publisher"), attribute("Version")))
|
||||
"StoreId" -> storeIds.add(parser.nextText().trim())
|
||||
"MainPackageDependency" -> dependencies.add(attribute("Name"))
|
||||
"RelatedProduct" -> related.add(parser.nextText().trim())
|
||||
"Executable" -> {
|
||||
val path = attribute("Name").replace('\\', '/')
|
||||
if (path.endsWith(".exe", true) && attribute("TargetDeviceFamily") in listOf("", "PC", "Windows.Desktop") &&
|
||||
!attribute("IsDevOnly").equals("true", true)) entries.add(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
require(root && identities.size <= 1 && storeIds.size <= 1 && dependencies.size <= 1) { "Invalid Xbox game manifest." }
|
||||
val ids = related.distinct()
|
||||
require(ids.size <= 128 && ids.all { it.matches(Regex("[A-Z0-9]{12}")) })
|
||||
val identity = identities.singleOrNull()
|
||||
return Info(storeIds.singleOrNull().orEmpty(), identity?.get(0).orEmpty(), identity?.get(1).orEmpty(), identity?.get(2).orEmpty(),
|
||||
dependencies.singleOrNull().orEmpty(), ids, entries)
|
||||
}
|
||||
|
||||
fun executable(folder: File): String {
|
||||
for (path in read(folder).executables) {
|
||||
require(!path.startsWith('/') && !path.contains(':') && path.split('/').none { it == ".." || it.isEmpty() })
|
||||
var file = folder
|
||||
for (part in path.split('/')) {
|
||||
val matches = file.listFiles().orEmpty().filter { it.name.equals(part, true) }
|
||||
require(matches.size == 1) { "Missing or ambiguous Xbox launch path." }
|
||||
file = matches.single()
|
||||
}
|
||||
require(file.canonicalPath.startsWith(folder.canonicalPath + File.separator))
|
||||
if (file.isFile) return file.relativeTo(folder).invariantSeparatorsPath
|
||||
}
|
||||
error("The Xbox package has no supported PC launch executable.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.*
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
internal object XboxRuntime {
|
||||
private var child: Xodus.Child? = null
|
||||
private var owner: String? = null
|
||||
private val activeGames = HashMap<String, Int>()
|
||||
@Synchronized fun isActive(id: String): Boolean = activeGames.getOrDefault(id, 0) > 0
|
||||
@Synchronized fun released(id: String) {
|
||||
val count = activeGames.getOrDefault(id, 0)
|
||||
if (count <= 1) activeGames.remove(id) else activeGames[id] = count - 1
|
||||
}
|
||||
|
||||
@Synchronized fun prepare(app: Context, id: String): JSONObject {
|
||||
check(!XboxContent.busy(id)) { "Wait for Xbox content downloads to finish" }
|
||||
check(SessionState.running) { "No running DroidDeck session" }
|
||||
check(StoreGameSidecar.find(app, Store.XBOX, id)?.isInstalled == true) { "Xbox game is not installed" }
|
||||
val account = StoreAccounts.signedInAs(app, Store.XBOX) ?: error("Sign in to Xbox before playing")
|
||||
val socket = File(app.filesDir, "xbox-runtime/xodus.sock")
|
||||
if (child?.process?.isAlive != true || owner != account) {
|
||||
stop()
|
||||
socket.delete()
|
||||
val service = Xodus.start(app, emptyList(), service = true)
|
||||
child = service; owner = account
|
||||
Xodus.diagnostics(service)
|
||||
Thread({ runCatching { service.process.inputStream.use { val buffer = ByteArray(8192); while (it.read(buffer) >= 0) {} } } }, "xbox-service-output").start()
|
||||
val deadline = android.os.SystemClock.elapsedRealtime() + 90_000
|
||||
while (!socket.exists() && service.process.isAlive && SessionState.running && android.os.SystemClock.elapsedRealtime() < deadline) Thread.sleep(100)
|
||||
if (!socket.exists() || !service.process.isAlive || !SessionState.running) {
|
||||
stop(); error("Xbox account service did not become ready. Check your sign-in and network connection.")
|
||||
}
|
||||
}
|
||||
activeGames[id] = activeGames.getOrDefault(id, 0) + 1
|
||||
return JSONObject().put("ok", true).put("socket", socket.path).put("credentials", child!!.credentialSocket)
|
||||
}
|
||||
|
||||
@Synchronized fun stop() {
|
||||
val process = child; child = null; owner = null; activeGames.clear()
|
||||
runCatching { process?.close() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.json.JSONObject
|
||||
import java.io.Closeable
|
||||
import java.io.File
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
internal object Xodus {
|
||||
const val DIR = "/usr/local/lib/droiddeck-xbox"
|
||||
fun market(): String = java.util.Locale.getDefault().country.uppercase().takeIf { it.matches(Regex("[A-Z]{2}")) } ?: "US"
|
||||
|
||||
class Child(val process: Process, private val credentials: XboxCredentials) : Closeable {
|
||||
val credentialSocket: String get() = credentials.name
|
||||
@Synchronized fun send(frame: JSONObject) {
|
||||
process.outputStream.write((frame.toString() + "\n").toByteArray())
|
||||
process.outputStream.flush()
|
||||
}
|
||||
override fun close() {
|
||||
process.destroy()
|
||||
if (!process.waitFor(2, TimeUnit.SECONDS)) process.destroyForcibly()
|
||||
credentials.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized private fun stage(app: Context) {
|
||||
val root = File(LinuxRuntime.rootDir(app), DIR.removePrefix("/"))
|
||||
val packaged = app.assets.open("linuxfs$DIR/version").bufferedReader().use { it.readText() }
|
||||
if (runCatching { File(root, "version").readText() }.getOrNull() == packaged) return
|
||||
fun copy(relative: String) {
|
||||
val entries = app.assets.list("linuxfs$DIR/$relative").orEmpty()
|
||||
if (entries.isNotEmpty()) { entries.forEach { copy(if (relative.isEmpty()) it else "$relative/$it") }; return }
|
||||
if (relative == "version") return
|
||||
val file = File(root, relative)
|
||||
file.parentFile?.mkdirs()
|
||||
val staged = File(file.path + ".staged")
|
||||
app.assets.open("linuxfs$DIR/$relative").use { input -> staged.outputStream().use { input.copyTo(it) } }
|
||||
staged.setExecutable(true, false)
|
||||
check(staged.renameTo(file))
|
||||
}
|
||||
copy("")
|
||||
File(root, "version").writeText(packaged)
|
||||
}
|
||||
|
||||
fun start(app: Context, args: List<String>, service: Boolean = false): Child {
|
||||
check(LinuxRuntime.isInstalled(app)) { "Install the Linux runtime before using Xbox." }
|
||||
stage(app)
|
||||
val binary = "$DIR/${if (service) "xodus-service" else "xodus-cli"}"
|
||||
check(File(LinuxRuntime.rootDir(app), binary.removePrefix("/")).isFile) { "The Xbox backend is missing. Update the Linux runtime." }
|
||||
val credentials = XboxCredentials(app)
|
||||
try {
|
||||
val runtime = File(app.filesDir, "xbox-runtime").apply { mkdirs() }
|
||||
val command = LinuxRuntime.command(app, null, null, Environment.getExternalStorageDirectory(), listOf(
|
||||
"/usr/bin/env", "HOME=/root", "XODUS_LOG=off", "RUST_LOG=off",
|
||||
"XDG_RUNTIME_DIR=${runtime.path}", "DROIDDECK_XBOX_CREDENTIAL_SOCKET=${credentials.name}", binary,
|
||||
) + args)
|
||||
val builder = ProcessBuilder(command).directory(LinuxRuntime.rootDir(app))
|
||||
builder.environment().apply {
|
||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
|
||||
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
return Child(builder.start(), credentials)
|
||||
} catch (e: Exception) { credentials.close(); throw e }
|
||||
}
|
||||
|
||||
fun run(app: Context, args: List<String>, timeout: Long = 90): JSONObject {
|
||||
start(app, args).use { child ->
|
||||
val output = java.io.ByteArrayOutputStream()
|
||||
var readError: Throwable? = null
|
||||
val reader = Thread({
|
||||
try {
|
||||
val buffer = ByteArray(8192)
|
||||
child.process.inputStream.use { input ->
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
check(output.size() + count <= 8_000_000)
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
}
|
||||
} catch (t: Throwable) { readError = t; child.process.destroy() }
|
||||
}, "xbox-result").apply { start() }
|
||||
val diagnostic = diagnostics(child)
|
||||
check(child.process.waitFor(timeout, TimeUnit.SECONDS)) { "Xbox request timed out. Try again." }
|
||||
reader.join(3000); diagnostic.join(3000)
|
||||
check(readError == null && !reader.isAlive) { "Xbox returned an invalid response." }
|
||||
check(child.process.exitValue() == 0) { "Xbox request failed. Check your account and network connection." }
|
||||
return JSONObject(output.toString("UTF-8"))
|
||||
}
|
||||
}
|
||||
|
||||
fun diagnostics(child: Child): Thread = Thread({
|
||||
runCatching {
|
||||
child.process.errorStream.bufferedReader().useLines { lines -> lines.forEach { line ->
|
||||
if (line.matches(Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.")))
|
||||
com.droiddeck.launcher.stores.StoresState.logLine("Xbox: $line")
|
||||
} }
|
||||
}
|
||||
}, "xbox-diagnostics").apply { start() }
|
||||
}
|
||||
@@ -29,6 +29,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
|
||||
Store.GOG.id -> SourceColours(Color(0xFF3A1A3C), Color(0xFFE6A3EA), Color(0xFFC25BC8))
|
||||
Store.EPIC.id -> SourceColours(Color(0xFF2A2A2A), Color(0xFFDDDDDD), Color(0xFFBDBDBD))
|
||||
Store.AMAZON.id -> SourceColours(Color(0xFF3A2A0A), Color(0xFFFFC266), Color(0xFFFF9900))
|
||||
Store.XBOX.id -> SourceColours(Color(0xFF17381B), Color(0xFFC6EDC2), Color(0xFF70C850))
|
||||
Store.ITCH.id -> SourceColours(Color(0xFF3A1A1E), Color(0xFFFFB3B3), Color(0xFFFF5C5C))
|
||||
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
|
||||
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
|
||||
@@ -41,6 +42,7 @@ internal fun sourceLabel(source: String): String = when (source) {
|
||||
Store.GOG.id -> Store.GOG.label
|
||||
Store.EPIC.id -> Store.EPIC.label
|
||||
Store.AMAZON.id -> Store.AMAZON.label
|
||||
Store.XBOX.id -> Store.XBOX.label
|
||||
Store.ITCH.id -> Store.ITCH.label
|
||||
else -> stringResource(R.string.source_added)
|
||||
}
|
||||
|
||||
@@ -97,7 +97,8 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
installed != null -> stringResource(R.string.stores_eyebrow_installed) + " · " + com.droiddeck.launcher.stores.StoreInstallRoot.labelFor(ctx, installed.folder)
|
||||
download != null && download.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + download.location
|
||||
failedDownload != null && failedDownload.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + failedDownload.location
|
||||
item?.owned == true -> stringResource(R.string.stores_eyebrow_library)
|
||||
item?.subscription == true -> "PC Game Pass"
|
||||
item?.accessible == true -> stringResource(R.string.stores_eyebrow_library)
|
||||
else -> stringResource(R.string.stores_eyebrow_store)
|
||||
}
|
||||
val size = (item?.sizeBytes ?: 0L).takeIf { it > 0 }?.let { " · " + formatBytes(it) } ?: ""
|
||||
@@ -118,12 +119,20 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
when {
|
||||
installed != null -> {
|
||||
val gone = StoresState.uninstalling["${store.id}:$id"]
|
||||
PrimaryButton(stringResource(R.string.stores_play), enabled = !s.busy && gone == null && download == null, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) {
|
||||
PrimaryButton(stringResource(R.string.stores_play), enabled = !s.busy && gone == null && download == null && (store != Store.XBOX || !com.droiddeck.launcher.stores.xbox.XboxContent.busy(id)), main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) {
|
||||
launchStoreGame(ctx, store, id, s, a)
|
||||
}
|
||||
ActionChip(stringResource(R.string.stores_in_steam), ok = true)
|
||||
if (store == Store.XBOX) {
|
||||
SecondaryButton("Update / verify", enabled = download == null && !com.droiddeck.launcher.stores.xbox.XboxRuntime.isActive(id)) {
|
||||
com.droiddeck.launcher.stores.xbox.XboxBackend.update(ctx, installed)
|
||||
}
|
||||
SecondaryButton("Manage content", enabled = download == null) {
|
||||
com.droiddeck.launcher.stores.xbox.XboxContent.manage(ctx, installed)
|
||||
}
|
||||
}
|
||||
if (gone != null) SecondaryButton(stringResource(R.string.stores_uninstalling), enabled = false, progress = gone) {}
|
||||
else UninstallButton(title, installed, enabled = download == null) {
|
||||
else UninstallButton(title, installed, enabled = download == null && (store != Store.XBOX || !com.droiddeck.launcher.stores.xbox.XboxContent.busy(id))) {
|
||||
StoresState.uninstall(ctx, installed) { StoresState.refresh(ctx); a.onLibraryChanged() }
|
||||
}
|
||||
}
|
||||
@@ -143,11 +152,11 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
com.droiddeck.launcher.stores.download.DownloadQueue.clear(ctx, failedDownload.key)
|
||||
}
|
||||
}
|
||||
item?.owned == true && StoresState.isUnfinished(item) -> {
|
||||
item?.accessible == true && StoresState.isUnfinished(item) -> {
|
||||
InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
|
||||
}
|
||||
item?.owned == true -> InstallButton(
|
||||
item?.accessible == true -> InstallButton(
|
||||
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
|
||||
leadOn,
|
||||
) { StoresState.requestInstall(ctx, item) }
|
||||
@@ -169,10 +178,10 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
}
|
||||
val description = item?.let { com.droiddeck.launcher.stores.cleanStoreText(it.description) }.orEmpty()
|
||||
.takeUnless { it.trim().equals(title.trim(), ignoreCase = true) }.orEmpty()
|
||||
val achievements = remember(store, id, item?.owned, installed) {
|
||||
val achievements = remember(store, id, item?.accessible, installed) {
|
||||
when {
|
||||
StoreAchievements.forSource(store.id) == null -> null
|
||||
item?.owned == true -> StoreAchievements.Game.of(item)
|
||||
item?.accessible == true -> StoreAchievements.Game.of(item)
|
||||
installed != null -> StoreAchievements.Game.of(installed.sidecar)
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -155,12 +155,41 @@ internal fun tabsFor(store: Store?): List<String> = if (store == Store.AMAZON) T
|
||||
|
||||
internal fun tabFor(store: Store?, tab: String): String = if (tab in tabsFor(store)) tab else "library"
|
||||
|
||||
private data class PaneKey(val chip: String, val tab: String, val signedIn: Boolean)
|
||||
private data class PaneKey(val chip: String, val tab: String, val signedIn: Boolean, val accountsLoaded: Boolean)
|
||||
|
||||
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class, androidx.compose.animation.ExperimentalAnimationApi::class)
|
||||
@Composable
|
||||
internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
|
||||
val ctx = LocalContext.current
|
||||
com.droiddeck.launcher.stores.xbox.XboxContent.plan?.let { content ->
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { com.droiddeck.launcher.stores.xbox.XboxContent.dismiss() },
|
||||
title = { Text("Xbox content") },
|
||||
text = { Column {
|
||||
if (content.error != null) Text(content.error)
|
||||
else if (content.offers.isEmpty()) Text("No licensed PC content packages are available for this game.")
|
||||
content.offers.forEach { offer ->
|
||||
androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxContent.install(ctx, offer.item) }) {
|
||||
Text(offer.item.title + if (offer.installed) " · Update / verify" else " · Install")
|
||||
}
|
||||
}
|
||||
} },
|
||||
confirmButton = { androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxContent.dismiss() }) { Text(stringResource(android.R.string.ok)) } },
|
||||
)
|
||||
}
|
||||
com.droiddeck.launcher.stores.xbox.XboxBackend.packageChoice?.let { pending ->
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { com.droiddeck.launcher.stores.xbox.XboxBackend.dismissPackages() },
|
||||
title = { Text("Choose PC content") },
|
||||
text = { Column { pending.choices.forEach { choice ->
|
||||
androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxBackend.selectPackage(ctx, choice) }) {
|
||||
Text(choice.getString("title") + " (" + choice.getString("kind") + ")")
|
||||
}
|
||||
} } },
|
||||
confirmButton = {},
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxBackend.dismissPackages() }) { Text(stringResource(android.R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val narrow = LocalNarrowPane.current
|
||||
val padH = if (narrow) 14.dp else 22.dp
|
||||
@@ -175,6 +204,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
val pane = PaneKey(
|
||||
chip, if (store == null) "" else shownTab,
|
||||
store == null || (StoresState.isSignedIn(store) && StoresState.expired[store] != true),
|
||||
store == null || StoresState.accountsLoaded,
|
||||
)
|
||||
val grids = remember { HashMap<PaneKey, LazyGridState>() }
|
||||
val grid = grids.getOrPut(pane) { LazyGridState() }
|
||||
@@ -362,6 +392,9 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
when {
|
||||
k.chip == DOWNLOADS -> Column(Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) { StoresDownloadsPane(s, a) }
|
||||
st == null -> {}
|
||||
!k.accountsLoaded -> Box(Modifier.fillMaxWidth().padding(top = 16.dp)) {
|
||||
androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
|
||||
}
|
||||
!k.signedIn -> Box(Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) { SignInCard(st, viewportH - 20.dp) }
|
||||
else -> Storefront(st, k.tab, query, s, a, grids.getOrPut(k) { LazyGridState() }, onQuery = { query = it }, onOpen = { open(it) }, onTab = { switchTab(it) })
|
||||
}
|
||||
@@ -541,10 +574,11 @@ private fun StoreChips(
|
||||
Box(
|
||||
Modifier.size(12.dp)
|
||||
.onGloballyPositioned { StoresMotion.dots[store] = it.boundsInRoot() }
|
||||
.pulseRing(StoresMotion.pulses[store] ?: 0, c.dot),
|
||||
) { Box(Modifier.matchParentSize().clip(CircleShape).background(c.dot).alpha(if (signedIn) 1f else 0.35f)) }
|
||||
.pulseRing(StoresMotion.pulses[store] ?: 0, c.dot)
|
||||
.background(c.dot.copy(alpha = if (signedIn) 1f else 0.35f), CircleShape),
|
||||
)
|
||||
},
|
||||
description = store.label + if (signedIn) "" else " " + stringResource(R.string.stores_chip_signed_out),
|
||||
description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out),
|
||||
onFocused = onFocusChip,
|
||||
) { onStore(store, rootBounds[store.id]) }
|
||||
}
|
||||
@@ -737,7 +771,7 @@ private fun Storefront(
|
||||
val q = query.trim().lowercase()
|
||||
val foundKeys = remember(found) { found.map { it.key }.toSet() }
|
||||
fun matches(i: CatalogItem) = q.isEmpty() || i.title.lowercase().contains(q) || i.key in foundKeys
|
||||
fun shown(i: CatalogItem) = s.storesShowMature || !i.mature || i.owned
|
||||
fun shown(i: CatalogItem) = s.storesShowMature || !i.mature || i.accessible
|
||||
fun shelf(l: List<CatalogItem>?) = l?.filter(::shown)
|
||||
val everything = remember(library, shelves, found) { (found + library + (shelves?.all ?: emptyList())).distinctBy { it.id } }
|
||||
LaunchedEffect(store, q) { StoresState.search(ctx, store, q) }
|
||||
@@ -788,7 +822,7 @@ private fun Storefront(
|
||||
CompletableFuture.allOf(*requests.map { it.second }.toTypedArray()).await()
|
||||
requests.forEach { (item, future) ->
|
||||
val bytes = future.getNow(null) ?: return@forEach
|
||||
if (item.owned && item.sizeBytes <= 0) com.droiddeck.launcher.stores.StoreSizes.known[item.key] = bytes
|
||||
if (item.accessible && item.sizeBytes <= 0) com.droiddeck.launcher.stores.StoreSizes.known[item.key] = bytes
|
||||
}
|
||||
resolvedSizeSortKey = candidateKeys
|
||||
}
|
||||
@@ -993,6 +1027,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
|
||||
Store.GOG -> Color(0xFFC25BC8) to Color(0xFF9A3FA1)
|
||||
Store.EPIC -> Color(0xFFE6E6E6) to Color(0xFFBDBDBD)
|
||||
Store.AMAZON -> Color(0xFFFF9900) to Color(0xFFE07800)
|
||||
Store.XBOX -> Color(0xFF70C850) to Color(0xFF107C10)
|
||||
Store.ITCH -> Color(0xFFFF5C5C) to Color(0xFFD93B3B)
|
||||
null -> return base
|
||||
}
|
||||
@@ -1259,7 +1294,7 @@ private fun GameCard(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.onGloballyPositioned { c ->
|
||||
placed[0] = c
|
||||
if (item.owned && item.sizeBytes <= 0) {
|
||||
if (item.accessible && item.sizeBytes <= 0) {
|
||||
val b = c.boundsInWindow()
|
||||
if (b.bottom > -ahead && b.top < screen + ahead && b.width > 0f) com.droiddeck.launcher.stores.StoreSizes.request(ctx, item)
|
||||
}
|
||||
@@ -1352,9 +1387,9 @@ private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droi
|
||||
Icon(Icons.Filled.Check, stringResource(R.string.stores_installed_chip), tint = pal.good, modifier = Modifier.size(11.dp))
|
||||
}
|
||||
download != null -> Text("${download.percent}%", fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
item.owned && StoresState.isUnfinished(item) -> Text(stringResource(R.string.stores_resume), fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
item.owned && compact -> Unit
|
||||
item.owned -> com.droiddeck.launcher.stores.StoreSizes.size(item).takeIf { it > 0 }?.let { Text(formatBytes(it), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1) }
|
||||
item.accessible && StoresState.isUnfinished(item) -> Text(stringResource(R.string.stores_resume), fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
item.accessible && compact -> Unit
|
||||
item.accessible -> com.droiddeck.launcher.stores.StoreSizes.size(item).takeIf { it > 0 }?.let { Text(formatBytes(it), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1) }
|
||||
item.isFree -> Text(stringResource(R.string.stores_free), fontSize = small, fontWeight = FontWeight.Bold, color = pal.good, maxLines = 1)
|
||||
item.isDiscounted -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
StateChip("-${item.discountPercent}%", ChipTone.DEAL, small = true)
|
||||
@@ -1430,9 +1465,16 @@ internal fun openUrl(ctx: android.content.Context, url: String) {
|
||||
|
||||
internal fun launchStoreGame(ctx: android.content.Context, store: Store, id: String, s: FrontEndState, a: FrontEndActions) {
|
||||
val game = s.steamGames.firstOrNull { it.source == store.id && it.storeId == id }
|
||||
if (game == null) {
|
||||
android.widget.Toast.makeText(ctx, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show()
|
||||
if (game != null) {
|
||||
com.droiddeck.launcher.stores.StoreLaunch.prepare(ctx, store, id) { a.onSteamGame(game) }
|
||||
return
|
||||
}
|
||||
com.droiddeck.launcher.stores.StoreLaunch.prepare(ctx, store, id) { a.onSteamGame(game) }
|
||||
val app = ctx.applicationContext
|
||||
Thread({
|
||||
val installed = runCatching { com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, store, id) }.getOrNull()
|
||||
StoresState.post {
|
||||
if (installed == null) android.widget.Toast.makeText(ctx, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show()
|
||||
else com.droiddeck.launcher.stores.StoreLaunch.prepare(ctx, store, id) { a.onSteamGame(installed) }
|
||||
}
|
||||
}, "store-play").start()
|
||||
}
|
||||
Reference in new issue
Block a user