Compare commits

..
Author SHA1 Message Date
MaxsTechReview 54ca518553 fix(storage): a card library the session cannot open by its raw path is opened by its storage path (#3475)
A game storage folder saved as a raw volume path is opened through the volume's /storage path when only that one is usable, and its private directories are kept under either path. Battle.net is only given a library folder when the configured one is attached, so a missing card no longer moves its install folder to internal storage.
2026-11-30 12:00:05 -05:00
27 changed files with 173 additions and 2003 deletions

No files matched your search

@@ -1129,7 +1129,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
Thread({
val added = if (com.droiddeck.launcher.session.NoSteamLaunch.needsAddedGame(game)) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(app, game, added)
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added)
ui.post {
onHandled()
if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) {
@@ -1138,12 +1138,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
if (command == null) {
launchCoordinator.releaseHandling(request)
val message = if (game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) {
R.string.game_link_battlenet_missing
} else {
R.string.game_link_failed
}
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
return@post
}
com.droiddeck.launcher.session.NoSteamLaunch.remember(command)
@@ -42,7 +42,7 @@ object GameRemoval {
val folder = game.gameFiles ?: return null
val store = Store.byId(game.source)
val id = game.storeId
if (store != null && id != null) StoresState.installedGame(store, id, folder)?.let { return it }
if (store != null && id != null) StoresState.installedGame(store, id)?.let { return it }
val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.isInstalled } ?: return null
return InstalledStoreGame(sidecar, folder)
}
@@ -23,6 +23,7 @@ object BattleNet {
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary", flavor = "_anniversary_"),
Title("wow_forever", "World of Warcraft: Forever", "WoWF", shop = "world-of-warcraft-forever", product = "wowf", flavor = "_forever_"),
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii", product = "d3"),
Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"),
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii", product = "s2"),
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered", product = "s1"),
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone", product = "hsb"),
@@ -55,26 +56,10 @@ object BattleNet {
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
)
// d3cn is not a store card of its own any more; it resolves to the Diablo III title through CN_UIDS.
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.code != "WoWC" }
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
/**
* Blizzard's China client installs some products under a CN uid; they are the same games and keep their store
* identity. Only the launch code and the product served by the China repository can differ.
*/
private class Cnv(val uid: String, val code: String? = null, val product: String? = null)
private val CN_UIDS = mapOf(
"s2_cn" to Cnv("s2", product = "s2c"),
"osic" to Cnv("osi", product = "osic"),
"anbs_cn" to Cnv("anbs"),
"d3cn" to Cnv("diablo3", "D3CN", "d3cn"),
)
private fun cn(alias: Cnv): Title? = TITLES.firstOrNull { it.uid == alias.uid }?.let { title ->
if (alias.code == null && alias.product == null) title
else Title(title.uid, title.name, alias.code ?: title.code, title.steam, title.shop, alias.product ?: title.product, title.flavor)
}
// Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity.
private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs")
fun notInstalled(title: Title, installedIds: Collection<String?>) =
installedIds.mapNotNull { id -> id?.let(::title)?.code }.none { it == title.code }
@@ -90,7 +75,7 @@ object BattleNet {
private val coverLock = Any()
fun fetchCovers(context: Context, titles: List<Title> = TITLES.distinctBy { it.code }): Boolean = synchronized(coverLock) {
fun fetchCovers(context: Context, titles: List<Title> = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" }): Boolean = synchronized(coverLock) {
val art = com.droiddeck.launcher.frontend.AddedGameArt
val key = com.droiddeck.launcher.frontend.SteamGridDb.key(context)
var got = false
@@ -177,10 +162,10 @@ object BattleNet {
internal fun title(uid: String): Title? {
val id = uid.lowercase()
TITLES.firstOrNull { it.uid == id }?.let { return it }
CN_UIDS[id]?.let { return cn(it) }
CN_UIDS[id]?.let { alias -> TITLES.firstOrNull { it.uid == alias }?.let { return it } }
val base = id.substringBeforeLast('_', "")
if (base.isEmpty() || id.substringAfterLast('_') !in LOCALES) return null
return TITLES.firstOrNull { it.uid == base } ?: CN_UIDS[base]?.let { cn(it) }
return TITLES.firstOrNull { it.uid == base } ?: CN_UIDS[base]?.let { alias -> TITLES.firstOrNull { it.uid == alias } }
}
internal fun titleForProduct(product: String): Title? {
@@ -217,112 +202,6 @@ object BattleNet {
}
}
/**
* The launch code of the copy installed in [folder]. The store card's code is not enough:
* a China client installs Diablo III under `D3CN` while the store title is `D3`.
*/
fun launchCode(context: Context, uid: String, folder: File?): String? {
if (folder == null) return runCatching { games(context) }.getOrNull()?.let { launchCode(it, uid, null) }
if (!folder.isDirectory) return null
return runCatching { installedRegistrationAt(context, uid, folder) }.getOrNull()?.second?.code
}
/**
* Two uids name the same store title: the China aliases fold into the store uid, and fen/fenris
* share one product under uids of their own.
*/
internal fun sameTitle(left: String, right: String): Boolean {
val a = title(left)
val b = title(right)
if (a == null || b == null) return left.equals(right, ignoreCase = true)
return a.uid == b.uid || (a.code == b.code && a.product != null && a.product == b.product)
}
/** False when a registration source exists but cannot be read: "no game here" is not a fact then. */
internal fun registrationsReadable(context: Context): Boolean {
val pfx = File(prefix(context), "pfx")
val agent = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
val registry = File(pfx, "system.reg")
if (agent.exists() && runCatching { productDbRegistrations(agent.readBytes()) }.getOrNull() == null) return false
if (registry.isFile && runCatching { registry.useLines { uninstallEntries(it) } }.isFailure) return false
return true
}
internal fun launchCode(games: List<Game>, uid: String, folder: File?): String? {
val canonical = title(uid)?.uid ?: uid
val same = games.filter { it.uid == canonical }
if (folder != null) return same.firstOrNull { it.folder.absolutePath == folder.absolutePath }?.code
return same.singleOrNull()?.code ?: title(uid)?.code
}
internal fun installedRegistrationAt(context: Context, id: String, folder: File): Pair<String, Title>? {
if (!folder.isDirectory) return null
val pfx = File(prefix(context), "pfx")
val agentFile = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
val registryFile = File(pfx, "system.reg")
val agent = if (agentFile.exists()) {
val bytes = agentFile.readBytes()
if (productDbRegistrations(bytes) == null) return null
productDbInstalls(bytes).orEmpty()
} else null
val registry = if (registryFile.exists()) registryFile.useLines { uninstallEntries(it) } else emptyList()
val candidates = if (agent == null) registry.map { AgentInstall(it.first, it.second, "") }
else agent
return candidates.firstNotNullOfOrNull { row ->
val found = title(row.uid) ?: titleForProduct(row.product) ?: return@firstNotNullOfOrNull null
if (!sameTitle(found.uid, id)) return@firstNotNullOfOrNull null
val registered = hostFolder(context, row.path) ?: return@firstNotNullOfOrNull null
if (registered.absolutePath != folder.absolutePath &&
(found.flavor != folder.name || registered.absolutePath != folder.parentFile?.absolutePath)
) return@firstNotNullOfOrNull null
row.uid to found
}
}
/** A registration for any title in this tree makes recursive deletion unsafe. */
internal fun folderHasRegistrations(context: Context, folder: File): Boolean? = runCatching {
val pfx = File(prefix(context), "pfx")
val agentFile = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
val registryFile = File(pfx, "system.reg")
val agent = if (agentFile.exists()) productDbRegistrations(agentFile.readBytes()) ?: return null else emptyList()
val registry = if (registryFile.exists()) registryFile.useLines { uninstallEntries(it) } else emptyList()
val target = folder.canonicalFile.toPath()
(agent.map { it.path } + registry.map { it.second }).any { path ->
val registered = hostFolder(context, path)?.canonicalFile?.toPath() ?: return null
registered.startsWith(target)
}
}.getOrNull()
internal fun registrationsAt(context: Context, id: String, folder: File): List<String>? {
val pfx = File(prefix(context), "pfx")
val agentFile = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
val registryFile = File(pfx, "system.reg")
val agent = if (!agentFile.exists()) emptyList()
else runCatching { productDbRegistrations(agentFile.readBytes()) }.getOrNull() ?: return null
val registry = if (!registryFile.exists()) emptyList()
else runCatching { registryFile.useLines { uninstallEntries(it) } }.getOrNull() ?: return null
val products = agent.filter { it.product.isNotEmpty() }.associate { it.uid.lowercase() to it.product }
val requested = title(id)
val flavor = requested?.flavor
val folders = buildSet {
add(folder.absolutePath)
if (flavor != null && folder.name == flavor) folder.parentFile?.let { add(it.absolutePath) }
}
if (agent.any { it.uid.isEmpty() && hostFolder(context, it.path)?.absolutePath in folders }) return null
val agentFolders = agent.filter { it.uid.isNotEmpty() }.groupBy { it.uid.lowercase() }.mapValues { (_, rows) ->
rows.mapNotNull { hostFolder(context, it.path)?.absolutePath }.toSet()
}
val registryRows = registry.filter { (uid, _) ->
val recorded = agentFolders[uid.lowercase()] ?: return@filter true
recorded.any { it in folders }
}
return (registryRows + agent.map { it.uid to it.path }).mapNotNull { (uid, path) ->
if (hostFolder(context, path)?.absolutePath !in folders) return@mapNotNull null
val title = title(uid) ?: products[uid.lowercase()]?.let(::titleForProduct)
if (title != null && sameTitle(title.uid, id)) uid else null
}.distinct()
}
internal fun ownFolders(games: Map<String, Pair<Title, File>>, saved: Map<String, String?>): Map<String, File> {
val out = HashMap<String, File>()
val taken = HashSet<File>()
@@ -438,25 +317,6 @@ object BattleNet {
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? = productDbInstalls(bytes)?.map { it.uid to it.path }
/**
* Every registration, including the one an unfinished install or update leaves behind:
* `productDbInstalls()` drops entries whose installed flag is 0, which is the state a
* cancelled download is in while its folder already holds data.
*/
internal fun productDbRegistrations(bytes: ByteArray): List<AgentInstall>? {
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 } ?: return null
return installs.mapNotNull { (_, start, end) ->
runCatching {
val install = fields(bytes, start, end)
val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) }
val product = install.firstOrNull { it.first == 2 }?.let { String(bytes, it.second, it.third - it.second) }.orEmpty()
val path = install.firstOrNull { it.first == 3 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
?.let { String(bytes, it.second, it.third - it.second) }
if (path.isNullOrEmpty()) null else AgentInstall(uid.orEmpty(), path, product)
}.getOrElse { return null }
}
}
internal fun productDbInstalls(bytes: ByteArray): List<AgentInstall>? {
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 }?.takeIf { it.isNotEmpty() } ?: return null
return installs.map { (_, start, end) ->
@@ -59,13 +59,18 @@ object GameStorage {
return when {
pref == SessionPrefs.GAME_STORAGE_OFF -> null
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.name, it.path) }
else -> Option(SessionPrefs.gameStorageLabel(context), pref).takeIf { attached(File(pref)) }
else -> reachable(pref).let { path -> Option(SessionPrefs.gameStorageLabel(context), path).takeIf { attached(File(path)) } }
}
}
fun disconnected(context: Context): Boolean {
val pref = SessionPrefs.gameStorage(context)
return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(pref))
return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(reachable(pref)))
}
internal fun reachable(path: String, usable: (File) -> Boolean = { it.isDirectory && it.canWrite() }): String {
val alias = UsbLink.storagePath(path)
return if (alias != path && !usable(File(path)) && usable(File(alias))) alias else path
}
internal fun attached(
@@ -38,13 +38,11 @@ object NoSteamLaunch {
else -> null
}?.takeIf { it.isNotEmpty() && GameEnvironment.validScope(it) }
fun battleNetTitleScope(context: Context, code: String): String? {
val games = runCatching { com.droiddeck.launcher.runtime.BattleNet.games(context) }.getOrDefault(emptyList())
return AddedGames.scan(context).firstOrNull { game ->
fun battleNetTitleScope(context: Context, code: String): String? =
AddedGames.scan(context).firstOrNull { game ->
game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id &&
game.storeId?.let { com.droiddeck.launcher.runtime.BattleNet.launchCode(games, it, game.folder) } == code
game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.code == code
}?.let { settingsId(it).toString() }
}
fun resolution(config: GameEnvironment.Config, scope: String?, output: Pair<Int, Int>): Pair<Int, Int>? {
val choice = scope?.let { GameEnvironment.gameResolution(config, it) } ?: return null
@@ -56,11 +54,10 @@ object NoSteamLaunch {
private fun viaBattleNet(game: Library.SteamGame): Boolean =
game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id
fun command(context: Context, game: Library.SteamGame, added: AddedGames.Game?): Command? = when {
fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when {
game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name)
viaBattleNet(game) ->
game.storeId?.let { com.droiddeck.launcher.runtime.BattleNet.launchCode(context, it, game.gameFiles) }
?.let { Command(BATTLENET, listOf("launch", it), game.name) }
game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.let { Command(BATTLENET, listOf("launch", it.code), game.name) }
game.library == Library.ADDED -> added?.let { a -> a.steamAppId?.let { Command(PROTON_RUN, listOf("--app", it.toString()), a.name) } ?: addedCommand(a) }
game.appId > 0 -> Command(PROTON_RUN, listOf("--app", game.appId.toString()), game.name)
else -> null
@@ -46,7 +46,16 @@ object SecondaryLibrary {
}
fun privateRoot(files: File, library: File): File {
val digest = MessageDigest.getInstance("SHA-256").digest(library.canonicalPath.toByteArray())
val own = privateDir(files, library.canonicalPath)
if (own.exists()) return own
val raw = UsbLink.rawPath(library.absolutePath)
val alias = if (raw != library.absolutePath) raw else UsbLink.storagePath(library.absolutePath)
if (alias == library.absolutePath) return own
return privateDir(files, runCatching { File(alias).canonicalPath }.getOrDefault(alias)).takeIf { it.exists() } ?: own
}
private fun privateDir(files: File, path: String): File {
val digest = MessageDigest.getInstance("SHA-256").digest(path.toByteArray())
.joinToString("") { "%02x".format(it.toInt() and 255) }
return File(files, "steam-libraries/$digest")
}
@@ -79,7 +79,6 @@ object StoresState {
fun refresh(context: Context) {
val app = context.applicationContext
com.droiddeck.launcher.stores.download.SavedQueue.restore(app)
com.droiddeck.launcher.stores.battlenet.BattleNetInstall.reconcile(app)
if (refreshRequests.getAndIncrement() > 0) return
var seen = 0
background("stores-refresh", onFailure = { if (refreshRequests.getAndSet(0) > seen) main.post { refresh(app) } }) {
@@ -104,8 +103,6 @@ object StoresState {
accountsLoaded = true
}
com.droiddeck.launcher.stores.gog.GogMaintenance.checkInstalled(app, onDisk)
onDisk.filter { it.sidecar.store == Store.BATTLENET }
.forEach { com.droiddeck.launcher.stores.battlenet.BattleNetInstall.checkUpdate(app, it) }
}
} while (!refreshRequests.compareAndSet(seen, 0))
}
@@ -140,16 +137,7 @@ object StoresState {
StoreInstalls.discard(app, folder, listOf(java.io.File(folder, ".chunks"), java.io.File(folder, ".gog_chunks"), StoreInstallRoot.scratchDir(app, item.store, item.id)))
}
fun installedGame(store: Store, id: String, folder: java.io.File? = null): InstalledStoreGame? =
pickInstalled(store, id, folder, installed)
internal fun pickInstalled(
store: Store, id: String, folder: java.io.File?, candidates: List<InstalledStoreGame>,
): InstalledStoreGame? {
val matches = candidates.filter { it.sidecar.store == store && it.sidecar.id == id }
if (folder != null) return matches.firstOrNull { it.folder.absolutePath == folder.absolutePath }
return matches.firstOrNull()
}
fun installedGame(store: Store, id: String): InstalledStoreGame? = installed.firstOrNull { it.sidecar.store == store && it.sidecar.id == id }
fun detailItem(store: Store, id: String): CatalogItem? = detailCatalogItem(
store, id, library[store].orEmpty(),
@@ -348,13 +336,9 @@ object StoresState {
private fun uninstallHeld(app: Context, game: InstalledStoreGame, key: String, onDone: () -> Unit) {
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
if (game.sidecar.store == Store.BATTLENET) {
val listed = com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }
// A registration we could not read is not the same as no registration: keep the folder.
if (listed || com.droiddeck.launcher.runtime.BattleNet.folderHasRegistrations(app, game.folder) != false) {
main.post { uninstalling.remove(key); onDone() }
return
}
if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) {
main.post { uninstalling.remove(key); onDone() }
return
}
StoreInstalls.uninstall(app, game, progress = { f -> main.post { if (key in uninstalling) uninstalling[key] = f } }, removed = {
main.post {
@@ -1,129 +0,0 @@
package com.droiddeck.launcher.stores.battlenet
import android.content.Context
import android.util.Log
import org.json.JSONObject
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
/**
* A cancelled Battle.net install that could not be cleaned up yet. The marker is written before
* the cleanup starts and removed only after the registration and the folder are both gone, so a
* restart can reconcile a registration that the client writes late.
*/
internal object BattleNetCleanup {
private const val TAG = "BattleNetCleanup"
private const val DIR = "battlenet-cleanup"
internal const val ACTIVE = "active"
internal const val PENDING = "pending"
internal const val WATCHING = "watching"
internal data class Pending(
val folder: File,
val id: String,
val createdFolder: Boolean,
val state: String,
val attempts: Int,
val nextAt: Long,
val stamp: Long,
)
internal fun dir(context: Context): File = File(context.filesDir, DIR)
@Synchronized
internal fun mark(context: Context, folder: File, id: String, createdFolder: Boolean, state: String = ACTIVE) {
val current = get(context, folder)
write(
context,
Pending(folder, id, createdFolder || current?.createdFolder == true, state, current?.attempts ?: 0, current?.nextAt ?: 0L, System.nanoTime()),
)
}
@Synchronized
internal fun markActive(context: Context, folder: File, id: String, createdFolder: Boolean) {
val current = get(context, folder)
write(
context,
Pending(
folder, id, createdFolder || current?.createdFolder == true,
current?.state?.takeIf { it != ACTIVE } ?: ACTIVE,
current?.attempts ?: 0, current?.nextAt ?: 0L, System.nanoTime(),
),
)
}
@Synchronized
internal fun update(context: Context, folder: File, state: String, attempts: Int, nextAt: Long) {
val current = get(context, folder) ?: return
write(context, current.copy(state = state, attempts = attempts, nextAt = nextAt))
}
@Synchronized
internal fun get(context: Context, folder: File): Pending? {
val file = file(context, folder)
val json = runCatching { JSONObject(file.readText()) }.getOrNull() ?: return null
return runCatching {
Pending(
folder = File(json.getString("folder")),
id = json.getString("id"),
createdFolder = json.optBoolean("createdFolder"),
state = json.optString("state", PENDING),
attempts = json.optInt("attempts"),
nextAt = json.optLong("nextAt"),
stamp = json.optLong("stamp"),
)
}.getOrNull()
}
internal fun pending(context: Context): List<Pending> = dir(context).listFiles()
?.filter { it.isFile && it.name.endsWith(".json") }
?.mapNotNull { file -> runCatching { JSONObject(file.readText()) }.getOrNull() }
?.mapNotNull { json ->
runCatching {
Pending(
folder = File(json.getString("folder")),
id = json.getString("id"),
createdFolder = json.optBoolean("createdFolder"),
state = json.optString("state", PENDING),
attempts = json.optInt("attempts"),
nextAt = json.optLong("nextAt"),
stamp = json.optLong("stamp"),
)
}.getOrNull()
}
?.filter { it.state != ACTIVE }
?.sortedBy { it.nextAt }
.orEmpty()
@Synchronized
internal fun clear(context: Context, folder: File) {
file(context, folder).delete()
}
private fun file(context: Context, folder: File) =
File(dir(context), MessageDigest.getInstance("SHA-256").run {
update(folder.absolutePath.toByteArray())
digest().joinToString("") { "%02x".format(it.toInt() and 0xff) }
} + ".json")
private fun write(context: Context, pending: Pending) {
val target = file(context, pending.folder)
target.parentFile?.mkdirs()
val json = JSONObject().apply {
put("folder", pending.folder.absolutePath)
put("id", pending.id)
put("createdFolder", pending.createdFolder)
put("state", pending.state)
put("attempts", pending.attempts)
put("nextAt", pending.nextAt)
put("stamp", pending.stamp)
}
val tmp = File(target.parentFile, "${target.name}.tmp")
runCatching {
tmp.writeText(json.toString())
Files.move(tmp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING)
}.onFailure { Log.w(TAG, "could not write ${target.path}", it) }
}
}
@@ -12,13 +12,11 @@ import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.SavedQueue
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
@@ -37,10 +35,7 @@ object BattleNetInstall {
private const val CN = "cn"
private const val BUILD_INFO = ".build.info"
private const val CHECK_AGAIN_MS = 30 * 60_000L
private const val CHECK_RETRY_MS = 30_000L
private const val CHECK_RETRY_MAX = 2
private const val START_WAIT_MS = 60_000L
private val reconciling = AtomicBoolean(false)
/** Blizzard serves China from battlenet.com.cn; its global version hostnames do not answer for that region. */
internal fun versionsUrl(region: String, product: String): String =
@@ -54,32 +49,11 @@ object BattleNetInstall {
internal val checks = Executors.newSingleThreadExecutor { r -> Thread(r, "battlenet-updates") }
internal val checkedAt = HashMap<String, Long>()
private val checkAttempts = java.util.concurrent.ConcurrentHashMap<String, Int>()
private val checkRetry = Executors.newSingleThreadScheduledExecutor { r ->
Thread(r, "battlenet-update-retry").apply { isDaemon = true }
}
/** Test seams: the version service and the delayed re-check. */
internal var fetchVersions: (String) -> String = ::fetch
internal var scheduleRecheck: (() -> Unit, Long) -> Unit = { body, delay ->
checkRetry.schedule(Runnable { body() }, delay, TimeUnit.MILLISECONDS)
}
val updates = mutableStateMapOf<String, Boolean>()
fun updateKey(id: String, folder: File?): String = "$id@${folder?.absolutePath ?: ""}"
fun product(id: String): String? = BattleNet.title(id)?.product
/** The China client serves StarCraft II, Diablo II and Diablo III from products of their own; anbs_cn shares anbs. */
private val CN_PRODUCTS = mapOf(
"osi" to "osic",
"s2" to "s2c",
"diablo3" to "d3cn",
)
internal fun chinaProduct(id: String): String? = CN_PRODUCTS[id]
fun headless(item: CatalogItem): Boolean = item.store == Store.BATTLENET && product(item.id) != null
internal fun locale(locale: Locale): String {
@@ -113,31 +87,19 @@ object BattleNetInstall {
fun enqueue(context: Context, item: CatalogItem, folder: File, update: Boolean = false) {
val app = context.applicationContext
val recorded = item.extra[PREEXISTING]
val tagged = if (recorded == "0" || recorded == "1") item
else item.copy(extra = item.extra + (PREEXISTING to "pending"))
val entry = DownloadEntry(
Store.BATTLENET, tagged.id, tagged.title, cover = tagged.tallImageUrl ?: tagged.imageUrl,
Store.BATTLENET, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl,
location = StoreInstallRoot.labelFor(app, folder),
cleanupKey = "${Store.BATTLENET.id}:${tagged.id}",
)
val ownership = Ownership(tagged)
DownloadQueue.enqueue(app, entry, onAccepted = {
SavedQueue.remember(app, tagged, folder.parentFile?.parentFile)
}) { BattleNetInstaller(app, tagged, folder, update, ownership) }
DownloadQueue.enqueue(app, entry) { BattleNetInstaller(app, item, folder, update) }
}
fun update(context: Context, game: InstalledStoreGame) {
val app = context.applicationContext
Thread({
val uid = installUid(app, game)
if (uid == null) {
Log.w(TAG, "no Battle.net install matches ${game.folder}")
StoresState.logLine("Battle.net: no registration matches ${game.folder.name}; update it from Battle.net")
StoresState.post { updates.remove(updateKey(game.sidecar.id, game.folder)) }
} else {
enqueue(app, updateItem(game, uid), game.folder, update = true)
}
val item = updateItem(game, installUid(app, game))
game.folder.parentFile?.parentFile?.let { com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, it) }
enqueue(app, item, game.folder, update = true)
}, "battlenet-update").start()
}
@@ -149,120 +111,17 @@ object BattleNetInstall {
internal fun updateFolder(item: CatalogItem): File? = item.extra[UPDATE_FOLDER]?.let(::File)
internal const val INSTALL_UID = "installUid"
internal const val PREEXISTING = "preexisting"
internal const val UPDATE_FOLDER = "updateFolder"
internal const val STALLED = "stalled"
/** The registration of this folder: games() keeps one copy per launch code, so a second copy is not in it. */
internal fun installUid(context: Context, game: InstalledStoreGame): String? =
runCatching { BattleNet.installedRegistrationAt(context, game.sidecar.id, game.folder) }.getOrNull()?.first
internal fun installUid(context: Context, game: InstalledStoreGame): String =
runCatching { BattleNet.games(context).firstOrNull { it.uid == game.sidecar.id }?.installUid }.getOrNull() ?: game.sidecar.id
fun uninstall(context: Context, game: InstalledStoreGame): Boolean {
if (product(game.sidecar.id) == null || !BattleNet.installed(context)) return false
val uid = installUid(context, game) ?: return false
val done = agentUninstall(context, uid)
val gone = registrationsGone(context, game.sidecar.id, game.folder, UNINSTALL_VERIFY_MS)
if (gone == null || gone.isNotEmpty()) {
Log.w(TAG, "uninstall $uid: the registration in ${game.folder.path} is still there")
return false
}
if (!done) Log.i(TAG, "uninstall $uid: registration gone after the Agent stopped")
BattleNetCleanup.clear(context, game.folder)
StoresState.post { StoresState.notifyLibraryChanged(context.applicationContext) }
return true
}
internal fun registrationsGone(context: Context, id: String, folder: File, timeoutMs: Long): List<String>? {
val deadline = System.currentTimeMillis() + timeoutMs
while (true) {
val found = runCatching { BattleNet.registrationsAt(context, id, folder) }.getOrNull() ?: return null
if (found.isEmpty() || System.currentTimeMillis() >= deadline) return found
Thread.sleep(250)
}
}
/**
* Retries the markers a cancelled install leaves when the registration it wrote is still
* present, or when it wrote one after the cancellation had already looked.
*/
fun reconcile(context: Context) {
val app = context.applicationContext
if (BattleNetCleanup.pending(app).isEmpty()) return
if (!reconciling.compareAndSet(false, true)) return
Thread({
try {
reconcileNow(app)
} finally {
reconciling.set(false)
}
}, "battlenet-cleanup-reconcile").start()
}
internal fun reconcileNow(
context: Context,
uninstall: (String) -> Boolean = { agentUninstall(context, it) },
verifyMs: Long = CLEANUP_VERIFY_MS,
watchMs: Long = CLEANUP_WATCH_MS,
) {
val now = System.currentTimeMillis()
for (pending in BattleNetCleanup.pending(context)) {
if (pending.nextAt > now) continue
if (pending.folder.absolutePath in cleanupRunning) continue
if (StoreInstalls.isDiscarding(pending.folder)) continue
val key = DownloadEntry(Store.BATTLENET, pending.id, pending.id).key
if (!DownloadQueue.holdForRemoval(key)) continue
try {
val current = BattleNetCleanup.get(context, pending.folder)
if (current == null || current.stamp != pending.stamp || current.id != pending.id ||
current.createdFolder != pending.createdFolder || current.state != pending.state ||
current.attempts != pending.attempts || current.nextAt != pending.nextAt
) continue
val found = runCatching { BattleNet.registrationsAt(context, pending.id, pending.folder) }.getOrNull()
if (found == null) {
retry(context, pending, "the registrations could not be read")
continue
}
if (found.isEmpty()) {
if (pending.createdFolder && pending.folder.exists() && !deleteFolder(pending.folder)) {
retry(context, pending, "the folder could not be deleted")
continue
}
if (pending.state == BattleNetCleanup.WATCHING && pending.attempts < CLEANUP_MAX_ATTEMPTS) {
BattleNetCleanup.update(context, pending.folder, BattleNetCleanup.WATCHING, pending.attempts + 1, now + watchMs)
continue
}
BattleNetCleanup.clear(context, pending.folder)
Log.i(TAG, "cleanup of ${pending.folder.path}: no registration remains")
continue
}
for (uid in found) uninstall(uid)
val left = registrationsGone(context, pending.id, pending.folder, verifyMs)
if (left == null || left.isNotEmpty()) {
retry(context, pending, "the registration in ${pending.folder.path} is still there")
continue
}
if (pending.createdFolder && pending.folder.exists() && !deleteFolder(pending.folder)) {
retry(context, pending, "the folder could not be deleted")
continue
}
BattleNetCleanup.clear(context, pending.folder)
Log.i(TAG, "cleanup of ${pending.folder.path}: ${if (pending.createdFolder) "removed" else "registration removed; folder kept"}")
} finally {
DownloadQueue.releaseRemoval(key)
}
}
}
private fun retry(context: Context, pending: BattleNetCleanup.Pending, reason: String) {
val attempts = pending.attempts + 1
val delay = if (attempts >= CLEANUP_MAX_ATTEMPTS) 10 * 60_000L else CLEANUP_RETRY_MS
BattleNetCleanup.update(context, pending.folder, pending.state, attempts, System.currentTimeMillis() + delay)
Log.w(TAG, "cleanup of ${pending.folder.path} is pending: $reason")
}
internal fun deleteFolder(folder: File): Boolean {
com.droiddeck.launcher.core.FileUtils.delete(folder)
return !folder.exists()
val done = agentUninstall(context, installUid(context, game))
if (done) StoresState.post { StoresState.notifyLibraryChanged(context.applicationContext) }
return done
}
internal fun agentUninstall(context: Context, uid: String): Boolean {
@@ -316,40 +175,21 @@ object BattleNetInstall {
internal fun check(id: String, folder: File, force: Boolean) {
val product = product(id) ?: return
val key = updateKey(id, folder)
val now = System.currentTimeMillis()
synchronized(checkedAt) {
if (!force && now - (checkedAt[key] ?: 0L) < CHECK_AGAIN_MS) return
// A new regular check starts a new retry cycle; a forced re-check does not.
if (!force) checkAttempts.remove(key)
checkedAt[key] = now
}
fun retryLater(reschedule: Boolean = false) {
synchronized(checkedAt) { if (checkedAt[key] == now) checkedAt.remove(key) }
StoresState.post { updates.remove(key) }
if (!reschedule) return
// A build that changed while the request ran can be checked again, but only a few times.
val attempt = checkAttempts.merge(key, 1) { old, _ -> old + 1 } ?: 1
if (attempt > CHECK_RETRY_MAX) return
scheduleRecheck({
Log.i(TAG, "$id: the build changed while checking; asking the version service again")
check(id, folder, force = true)
}, CHECK_RETRY_MS * attempt)
if (!force && now - (checkedAt[id] ?: 0L) < CHECK_AGAIN_MS) return
checkedAt[id] = now
}
fun retryLater() = synchronized(checkedAt) { if (checkedAt[id] == now) checkedAt.remove(id) }
checks.execute {
val local = runCatching { buildKey(File(folder, BUILD_INFO).readText()) }.getOrNull()
?: return@execute retryLater()
val served = if (local.first == CN) chinaProduct(id) ?: product else product
val latest = runCatching { latestBuild(fetchVersions(versionsUrl(local.first, served)), local.first) }
.onFailure { Log.w(TAG, "versions of $served: ${it.javaClass.simpleName}") }.getOrNull()
val latest = runCatching { latestBuild(fetch(versionsUrl(local.first, product)), local.first) }
.onFailure { Log.w(TAG, "versions of $product: ${it.javaClass.simpleName}") }.getOrNull()
?: return@execute retryLater()
val current = runCatching { buildKey(File(folder, BUILD_INFO).readText()) }.getOrNull()
?: return@execute retryLater()
if (current != local) return@execute retryLater(reschedule = true)
val behind = latest != current.second
val behind = latest != local.second
Log.i(TAG, "$id: ${if (behind) "update available" else "up to date"}")
StoresState.post { if (behind) updates[key] = true else updates.remove(key) }
checkAttempts.remove(key)
StoresState.post { if (behind) updates[id] = true else updates.remove(id) }
}
}
@@ -392,53 +232,22 @@ object BattleNetInstall {
private const val APPLY_PHASE = 2000
}
internal class Ownership(item: CatalogItem) {
@Volatile var known = item.extra[BattleNetInstall.PREEXISTING] in setOf("0", "1")
@Volatile var preexisting = item.extra[BattleNetInstall.PREEXISTING] == "1"
val createdFolder = AtomicBoolean(false)
}
internal class BattleNetInstaller(
private val app: Context,
private val item: CatalogItem,
private val folder: File,
private val update: Boolean,
private val ownership: Ownership = Ownership(item),
private val registrationWaitMs: Long = REGISTRATION_WAIT_MS,
private val cleanupVerifyMs: Long = CLEANUP_VERIFY_MS,
private val uninstall: (String) -> Boolean = { BattleNetInstall.agentUninstall(app, it) },
private val registration: () -> List<String>? = {
BattleNet.registrationsAt(app, item.id, folder)
},
) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private val cleanupStarted = AtomicBoolean(false)
private val started = AtomicBoolean(false)
private val queueKey = DownloadEntry(Store.BATTLENET, item.id, item.title).key
private val ended = java.util.concurrent.CountDownLatch(1)
private var before = 0L
private var kept = -1L
override fun run(handle: DownloadQueue.JobHandle): String? {
if (!cancelled.get() && !ownership.known) {
val found = runCatching { registration() }.getOrNull()
ownership.preexisting = found == null || found.isNotEmpty()
ownership.known = found != null
if (found != null) {
SavedQueue.remember(
app,
item.copy(extra = item.extra + (BattleNetInstall.PREEXISTING to if (ownership.preexisting) "1" else "0")),
folder.parentFile?.parentFile,
)
}
}
started.set(true)
try {
return if (cancelled.get()) null else work(handle)
} catch (t: Throwable) {
if (!cancelled.get()) BattleNetCleanup.clear(app, folder)
throw t
} finally {
ended.countDown()
}
@@ -451,10 +260,7 @@ internal class BattleNetInstaller(
val title = BattleNet.title(item.id)
val product = title?.product ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, item.id))
val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: title.uid
if (!update && folder.mkdirs()) {
ownership.createdFolder.set(true)
BattleNetCleanup.markActive(app, folder, item.id, createdFolder = true)
}
if (!update) folder.mkdirs()
val guest = AddedGames.guestPath(app, folder) ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, folder.path))
val (country, region) = BattleNetInstall.country(Locale.getDefault())
val args = if (update) listOf("agent-update", uid)
@@ -476,11 +282,10 @@ internal class BattleNetInstaller(
if (done == null) throw IllegalStateException(BattleNetInstall.failure(app, reason, code))
handle.log("Battle.net: ${item.title} ${if (update) "updated" else "installed"} ${done?.optString("version").orEmpty()}".trimEnd())
StoresState.post {
BattleNetInstall.updates.remove(BattleNetInstall.updateKey(item.id, folder))
BattleNetInstall.updates.remove(item.id)
StoresState.notifyLibraryChanged(app)
}
BattleNetInstall.check(item.id, folder, force = true)
BattleNetCleanup.clear(app, folder)
return folder.absolutePath
}
@@ -497,109 +302,17 @@ internal class BattleNetInstaller(
}
}
/**
* The client writes the install registration a little after the download starts; a cancel
* right after the request would otherwise read an empty list and leave the registration behind.
*/
private fun registrationsWaiting(): List<String>? {
val deadline = System.currentTimeMillis() + registrationWaitMs
while (true) {
val found = runCatching { registration() }.getOrNull() ?: return null
if (found.isNotEmpty() || System.currentTimeMillis() >= deadline) return found
Thread.sleep(250)
}
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (!deleteFiles || update) {
if (update) DownloadQueue.cleanupFinished(queueKey)
return
}
if (!cleanupStarted.compareAndSet(false, true)) return
if (!started.get() && !ownership.known) ownership.preexisting = true
val initialCreated = BattleNetCleanup.get(app, folder)?.createdFolder ?: ownership.createdFolder.get()
val path = folder.absolutePath
cleanupRunning.add(path)
if (!ownership.preexisting) {
BattleNetCleanup.mark(app, folder, item.id, initialCreated, BattleNetCleanup.PENDING)
}
val cleanup = Thread({
var discarding = false
try {
val stopped = !started.get() || ended.await(END_WAIT_S, TimeUnit.SECONDS)
val createdFolder = ownership.createdFolder.get() || (BattleNetCleanup.get(app, folder)?.createdFolder ?: false)
if (!ownership.preexisting && createdFolder != initialCreated) {
BattleNetCleanup.mark(app, folder, item.id, createdFolder, BattleNetCleanup.PENDING)
}
if (ownership.preexisting) {
BattleNetCleanup.clear(app, folder)
Log.i("BattleNetInstall", "cancelled install left the pre-existing registration in ${folder.path}")
} else if (!stopped) {
pending(createdFolder, "the cancelled install is still stopping")
} else {
StoreInstalls.beginDiscard(folder)
discarding = true
val created = registrationsWaiting()
if (created == null) {
pending(createdFolder, "the registrations could not be read")
} else if (created.isEmpty()) {
if (createdFolder && !BattleNetInstall.deleteFolder(folder)) {
pending(createdFolder, "the folder could not be deleted")
} else {
BattleNetCleanup.mark(app, folder, item.id, createdFolder, BattleNetCleanup.WATCHING)
BattleNetCleanup.update(app, folder, BattleNetCleanup.WATCHING, 0, System.currentTimeMillis() + CLEANUP_WATCH_MS)
Log.i("BattleNetInstall", "cancelled install of ${item.id}: no registration yet; watching ${folder.path}")
}
} else {
for (uid in created.distinct()) uninstall(uid)
val left = registrationsGoneHere(cleanupVerifyMs)
if (left == null || left.isNotEmpty()) {
pending(createdFolder, "the registration in ${folder.path} is still there")
} else if (createdFolder && !BattleNetInstall.deleteFolder(folder)) {
pending(createdFolder, "the folder could not be deleted")
} else {
BattleNetCleanup.clear(app, folder)
Log.i("BattleNetInstall", "cancelled install of ${created.first()}: ${if (createdFolder) "removed" else "registration removed; folder kept"}")
}
}
}
} finally {
cleanupRunning.remove(path)
if (discarding) StoreInstalls.endDiscard(folder)
DownloadQueue.cleanupFinished(queueKey)
}
}, "battlenet-cancel")
try {
cleanup.start()
} catch (t: Throwable) {
cleanupRunning.remove(path)
DownloadQueue.cleanupFinished(queueKey)
throw t
}
}
private fun pending(createdFolder: Boolean, reason: String) {
BattleNetCleanup.mark(app, folder, item.id, createdFolder, BattleNetCleanup.PENDING)
BattleNetCleanup.update(app, folder, BattleNetCleanup.PENDING, 1, System.currentTimeMillis() + CLEANUP_RETRY_MS)
Log.w("BattleNetInstall", "cleanup of ${folder.path} is pending: $reason")
}
private fun registrationsGoneHere(timeoutMs: Long): List<String>? {
val deadline = System.currentTimeMillis() + timeoutMs
while (true) {
val found = runCatching { registration() }.getOrNull() ?: return null
if (found.isEmpty() || System.currentTimeMillis() >= deadline) return found
Thread.sleep(250)
}
if (!deleteFiles || update) return
val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: BattleNet.title(item.id)?.uid ?: return
Thread({
if (started.get() && !ended.await(END_WAIT_S, TimeUnit.SECONDS)) Log.w("BattleNetInstall", "the cancelled install of $uid is still stopping")
val gone = BattleNetInstall.agentUninstall(app, uid)
if (folder.isDirectory && (gone || folder.list().isNullOrEmpty())) com.droiddeck.launcher.core.FileUtils.delete(folder)
Log.i("BattleNetInstall", "cancelled install of $uid: ${if (gone) "removed" else "left for Battle.net to remove"}")
}, "battlenet-cancel").start()
}
}
private const val END_WAIT_S = 120L
private const val REGISTRATION_WAIT_MS = 5_000L
private val cleanupRunning = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
private const val CLEANUP_VERIFY_MS = 30_000L
private const val CLEANUP_WATCH_MS = 15_000L
private const val CLEANUP_RETRY_MS = 60_000L
private const val CLEANUP_MAX_ATTEMPTS = 4
private const val UNINSTALL_VERIFY_MS = 30_000L
@@ -7,6 +7,7 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
@@ -130,13 +131,13 @@ object BattleNetClient {
StoresState.post { opener?.invoke(args) }
}
fun library(context: Context, root: File = preferred(context)): List<String> =
AddedGames.guestPath(context, StoreInstallRoot.storeDir(root, Store.BATTLENET))?.let { listOf("--library", it) }.orEmpty()
fun library(context: Context, root: File? = preferred(context)): List<String> =
root?.let { AddedGames.guestPath(context, StoreInstallRoot.storeDir(it, Store.BATTLENET)) }?.let { listOf("--library", it) }.orEmpty()
internal fun preferred(context: Context): File {
internal fun preferred(context: Context): File? {
val second = StoreInstallRoot.libraryRoot(context)?.absolutePath
return StoreInstallRoot.targets(context).firstOrNull { it.root.absolutePath == second && (it.root.isDirectory || it.root.mkdirs()) }?.root
?: StoreInstallRoot.internalRoot(context)
?: StoreInstallRoot.internalRoot(context).takeIf { second == null && !GameStorage.disconnected(context) }
}
fun installGame(context: Context, uid: String, root: File) {
@@ -24,6 +24,7 @@ internal object BlizzardArt {
"WoWC" to "${KEY_ART_ASSETS}blt6a80c8e7260f84f2/690d2219b415dd246153245b/BCC.png",
"WoWF" to "${KEY_ART_ASSETS}blt1d58537e928b17c5/6ae2c99668c747dd1b4f558b/WoW_Forever_AnimatedTrailerSupportAssets_BnetShop_1920x1080.png",
"D3" to "${KEY_ART_CATALOG}/f96/8d92f4d8bd316d3787f02d8a86935d6a-Store_Product_960x540_D3.jpg",
"D3CN" to "${KEY_ART_CATALOG}/f96/8d92f4d8bd316d3787f02d8a86935d6a-Store_Product_960x540_D3.jpg",
"S2" to "${KEY_ART_ASSETS}blt4b6d6857f147a6de/61254804841f180993fedb61/6885-32192.png",
"S1" to "${KEY_ART_ASSETS}blt03d69a4563a6ae63/6a34b50f799ece2cb2da248c/9458-28298.jpg",
"WTCG" to "${KEY_ART_ASSETS}blt5a3d84e1d0b2bbcf/662aea9f842cecfd4fd95327/HS_Key_Art_SG2.png",
@@ -34,7 +34,6 @@ data class DownloadEntry(
val interruptible: Boolean = true,
val reusedBytes: Long = 0L,
val appliedBytes: Long = 0L,
val cleanupKey: String? = null,
) {
fun passed(s: DownloadStage): Boolean = state == DownloadState.INSTALLED || (stagesPassed and (1 shl s.ordinal)) != 0
@@ -107,7 +107,6 @@ object DownloadQueue {
}
private val lock = Any()
private val cancelling = HashSet<String>()
private val items = LinkedHashMap<String, Item>()
private val heldPaused = HashSet<String>()
private val removing = HashSet<String>()
@@ -115,9 +114,7 @@ object DownloadQueue {
fun holdForRemoval(key: String): Boolean = synchronized(lock) {
val item = items[key]
if (item?.entry?.isActive == true || item?.job != null || key in cleaningUp || key in removing || key in cancelling) {
return@synchronized false
}
if (item?.entry?.isActive == true || item?.job != null || key in cleaningUp || key in removing) return@synchronized false
removing.add(key)
true
}
@@ -130,7 +127,7 @@ object DownloadQueue {
return synchronized(lock) {
while (true) {
val busy = busyLocked(key)
if (!busy && key !in cleaningUp && key !in removing && key !in cancelling) break
if (!busy && key !in cleaningUp && key !in removing) break
val left = deadline - android.os.SystemClock.uptimeMillis()
if (busy && left <= 0) return@synchronized false
(lock as Object).wait(if (busy) left else 0L)
@@ -195,31 +192,14 @@ object DownloadQueue {
fun isActive(key: String): Boolean = entry(key)?.isActive == true
fun isCancelling(key: String): Boolean = synchronized(lock) { key in cancelling }
internal fun cleanupFinished(key: String?) {
if (key == null) return
synchronized(lock) {
cancelling.remove(key)
(lock as Object).notifyAll()
}
}
fun anyActive(): Boolean = synchronized(lock) { items.values.any { it.entry.isActive } }
fun enqueue(context: Context, entry: DownloadEntry, onAccepted: (() -> Unit)? = null, factory: () -> DownloadJob): Boolean {
fun enqueue(context: Context, entry: DownloadEntry, factory: () -> DownloadJob) {
val app = context.applicationContext
synchronized(lock) {
val cleanupKey = entry.cleanupKey
if (cleanupKey != null && isCancelling(cleanupKey)) {
Log.i(TAG, "${entry.key}: previous cancellation is still cleaning up")
return false
}
if (entry.key in removing) { Log.i(TAG, "${entry.key}: being uninstalled"); return false }
items[entry.key]?.let { if (it.entry.isActive) { Log.i(TAG, "${entry.key}: already queued"); return false } }
if (entry.key in removing) { Log.i(TAG, "${entry.key}: being uninstalled"); return }
items[entry.key]?.let { if (it.entry.isActive) { Log.i(TAG, "${entry.key}: already queued"); return } }
items.remove(entry.key)
// The callback records the task's ownership snapshot; run it before advance() can see the item.
onAccepted?.invoke()
val state = if (heldPaused.remove(entry.key)) DownloadState.PAUSED else DownloadState.QUEUED
items[entry.key] = Item(entry.copy(state = state, stage = DownloadStage.MANIFEST, startedAt = System.currentTimeMillis()), factory)
renumber()
@@ -227,7 +207,6 @@ object DownloadQueue {
StoresState.logLine("${entry.store.label}: queued \"${entry.name}\"" + if (entry.bytesTotal > 0) " (${com.droiddeck.launcher.stores.formatBytes(entry.bytesTotal)})" else "")
publish(app)
advance(app)
return true
}
fun recordFailed(context: Context, entry: DownloadEntry, error: String, retry: (() -> Unit)? = null) {
@@ -295,39 +274,26 @@ object DownloadQueue {
val app = context.applicationContext
val item: Item
val wasRunning: Boolean
var cleanupKey: String? = null
var cleanup = false
var awaitDeletion: List<Thread> = emptyList()
synchronized(lock) {
item = items[key] ?: return
if (!item.entry.interruptible) return
val candidate = item.entry.cleanupKey?.takeIf { item.factory != null }
if (candidate != null && !cancelling.add(candidate)) {
Log.i(TAG, "$key: already cancelling")
return
}
cleanupKey = candidate
wasRunning = item.entry.state == DownloadState.RUNNING
if (wasRunning) {
item.pauseRequested = false
item.cancelled.set(true)
val deleting = StoreInstalls.collectingDiscards {
if (runCatching { item.job?.cancel(deleteFiles = true) }.isFailure) cleanupFinished(cleanupKey)
}
val deleting = StoreInstalls.collectingDiscards { runCatching { item.job?.cancel(deleteFiles = true) } }
if (deleting.isNotEmpty()) { holdCleanup(key); awaitDeletion = deleting }
}
if (!wasRunning) {
cleanup = beginCleanup(key)
if (!cleanup) cleanupFinished(cleanupKey)
item.entry = item.entry.copy(state = DownloadState.CANCELLED, queuePosition = 0, finishedAt = System.currentTimeMillis())
renumber()
publishLocked()
}
}
if (!wasRunning && cleanup) {
cleanUpLater(app, key, "store-dl-cancel") {
if (runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) }.isFailure) cleanupFinished(cleanupKey)
}
if (cleanup) {
cleanUpLater(app, key, "store-dl-cancel") { runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }
}
if (awaitDeletion.isNotEmpty()) cleanUpLater(app, key, "store-dl-cancel-wait") { awaitDeletion.forEach { it.join() } }
StoresState.logLine("cancelled \"${item.entry.name}\"")
@@ -337,27 +303,17 @@ object DownloadQueue {
}
fun clear(context: Context, key: String) {
val app = context.applicationContext
val item: Item
var cleanupKey: String? = null
var cleanup = false
val cleanup: Boolean
synchronized(lock) {
item = items[key] ?: return
if (item.entry.state == DownloadState.RUNNING || item.entry.state == DownloadState.QUEUED) return
if (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) {
val candidate = item.entry.cleanupKey?.takeIf { item.factory != null }
if (candidate == null || cancelling.add(candidate)) {
cleanup = beginCleanup(key)
if (cleanup) cleanupKey = candidate else cleanupFinished(candidate)
}
}
cleanup = (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) && beginCleanup(key)
items.remove(key)
publishLocked()
}
if (cleanup) cleanUpLater(app, key, "store-dl-clear") {
if (runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) }.isFailure) cleanupFinished(cleanupKey)
}
StoreDownloadService.finish(app, key)
if (cleanup) cleanUpLater(context.applicationContext, key, "store-dl-clear") { runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }
StoreDownloadService.finish(context.applicationContext, key)
}
fun dismissFinished() {
@@ -437,27 +393,11 @@ object DownloadQueue {
var error: String? = null
try {
val job = checkNotNull(item.factory).invoke()
var cancelled = false
var paused = false
synchronized(lock) {
item.job = job
cancelled = item.cancelled.get()
paused = item.pauseRequested
}
synchronized(lock) { item.job = job }
StoresState.logLine("${item.entry.store.label}: fetching manifest for \"${item.entry.name}\"")
val deleting = ArrayList<Thread>()
try {
StoreInstalls.collectingDiscards(deleting) {
if (cancelled) {
try {
job.cancel(deleteFiles = !paused)
} catch (t: Throwable) {
synchronized(lock) { cleanupFinished(item.entry.cleanupKey) }
throw t
}
}
result = job.run(handle)
}
StoreInstalls.collectingDiscards(deleting) { result = job.run(handle) }
} finally {
if (deleting.isNotEmpty()) {
holdCleanup(item.entry.key)
@@ -468,9 +408,6 @@ object DownloadQueue {
} catch (t: Throwable) {
error = t.message ?: t.javaClass.simpleName
Log.w(TAG, "${item.entry.key} failed", t)
synchronized(lock) {
if (item.job == null) cleanupFinished(item.entry.cleanupKey)
}
}
synchronized(lock) {
running--
@@ -29,16 +29,6 @@ object SavedQueue {
wanted[key(item)] = Wanted(item, root)
}
internal fun remembered(key: String): CatalogItem? = synchronized(this) { wanted[key]?.item }
internal fun resetForTest() {
synchronized(this) {
restored = false
wanted.clear()
app = null
}
}
fun save(entries: List<DownloadEntry>) {
val context = app ?: return
val rows = synchronized(this) {
@@ -177,7 +177,7 @@ internal fun GameDetail(
SideEffect { if (store != null && id != null) known[0] = store to id }
val game = found ?: if (store != null && id != null) s.steamGames.firstOrNull { it.source == store.id && it.storeId == id } else null
val item = if (store != null && id != null) StoresState.detailItem(store, id) else null
val installed = if (store != null && id != null) StoresState.installedGame(store, id, game?.gameFiles) else null
val installed = if (store != null && id != null) StoresState.installedGame(store, id) else null
val rawDownload = if (store != null && id != null) StoresState.download("${store.id}:$id") else null
val download = rawDownload?.takeIf { it.isActive }
val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED }
@@ -584,25 +584,12 @@ internal fun GameActions(
}
if (store == Store.BATTLENET) {
if (installed != null && id != null) {
val updateKey = BattleNetInstall.updateKey(id, installed.folder)
var wasRunning by remember(updateKey) { mutableStateOf(false) }
// SessionState.running is not snapshot state, so poll it while this detail is shown.
val sessionRunning by produceState(SessionState.running) {
while (true) {
value = SessionState.running
kotlinx.coroutines.delay(1000)
}
}
LaunchedEffect(updateKey, sessionRunning) {
val ended = wasRunning && !sessionRunning
wasRunning = sessionRunning
if (!sessionRunning) BattleNetInstall.checkUpdate(ctx, installed, force = ended)
}
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
if (download != null) {
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
} else if (BattleNetInstall.updates[updateKey] == true) {
} else if (BattleNetInstall.updates[id] == true) {
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
}
}
@@ -1198,22 +1198,8 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?, showDownlo
}
}
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean {
val installed = e.storeKey?.let { key ->
val store = Store.byId(e.source)
val id = e.item?.id ?: e.game?.storeId
if (store != null && id != null) StoresState.installedGame(store, id, e.game?.gameFiles)
else StoresState.installed.firstOrNull { it.key == key }
}
val battleNet = installed?.let {
com.droiddeck.launcher.stores.battlenet.BattleNetInstall.updates[
com.droiddeck.launcher.stores.battlenet.BattleNetInstall.updateKey(it.sidecar.id, it.folder)
] == true
} == true
return battleNet ||
e.storeKey?.let { it in ItchUpdates.available || it in GameJoltUpdates.available || it in com.droiddeck.launcher.stores.ea.EaUpdates.available } == true ||
e.source == Store.GOG.id && (e.item?.id ?: e.game?.storeId)?.let { GogMaintenance.checks[it]?.state } == GogMaintenance.State.AVAILABLE
}
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available || it in GameJoltUpdates.available || it in com.droiddeck.launcher.stores.ea.EaUpdates.available } == true ||
e.source == Store.GOG.id && (e.item?.id ?: e.game?.storeId)?.let { GogMaintenance.checks[it]?.state } == GogMaintenance.State.AVAILABLE
@Composable
private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, choose: (() -> Unit)?, onOpen: (String) -> Unit) {
-1
View File
@@ -1754,7 +1754,6 @@
<string name="game_link_program_unknown">Add this game to DroidDeck first, then start it from your frontend.</string>
<string name="game_link_session_busy">Stop the current session before launching a Steam game.</string>
<string name="game_link_failed">Could not send the game to Steam. Try launching it again.</string>
<string name="game_link_battlenet_missing">This Battle.net shortcut no longer matches an installed copy. Open Battle.net to repair or reinstall it.</string>
<string name="game_needs_app_model">%1$s is a UWP app. This runtime has no Windows app-model host to start it.</string>
<string name="setup_retry_removal">Retry removal</string>
<string name="runtime_removing">Removing</string>
@@ -3,17 +3,6 @@ package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.GameEnvironmentStore
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.battlenet.BattleNetCleanup
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
import com.droiddeck.launcher.stores.battlenet.BattleNetInstaller
import com.droiddeck.launcher.stores.battlenet.Ownership
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.github.luben.zstd.ZstdOutputStream
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
@@ -32,10 +21,6 @@ import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.nio.file.Files
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import java.util.zip.CRC32
private val REGISTRY = """
@@ -80,7 +65,6 @@ class BattleNetTest {
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
File(context.filesDir, "components").deleteRecursively()
File(context.filesDir, "battlenet-cleanup").deleteRecursively()
LinuxRuntime.rootDir(context).deleteRecursively()
}
@@ -361,511 +345,17 @@ class BattleNetTest {
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "osic"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo II Resurrected"))))),
field(1, message(field(1, "s2_cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/StarCraft II"))))),
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))),
))
for (folder in listOf("Diablo II Resurrected", "StarCraft II", "Diablo III")) {
for (folder in listOf("Diablo II Resurrected", "StarCraft II")) {
File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/$folder").mkdirs()
}
val games = BattleNet.games(context)
assertEquals(listOf("osic", "s2_cn", "d3cn"), games.map { it.installUid })
assertEquals(listOf("osi", "s2", "diablo3"), games.map { it.uid })
assertEquals(listOf("Diablo II: Resurrected" to "OSI", "StarCraft II" to "S2", "Diablo III" to "D3CN"), games.map { it.name to it.code })
assertEquals("osic", BattleNet.title("osic")?.product)
assertEquals("s2c", BattleNet.title("s2_cn")?.product)
assertEquals("anbs", BattleNet.title("anbs_cn")?.product)
assertEquals("d3cn", BattleNet.title("d3cn")?.product)
assertEquals("s2c", BattleNet.title("s2_cn_zhcn")?.product)
assertEquals("osic", BattleNet.title("osic_zhcn")?.product)
assertEquals("anbs", BattleNet.title("anbs_cn_zhcn")?.product)
}
assertEquals(listOf("osic", "s2_cn"), games.map { it.installUid })
assertEquals(listOf("osi", "s2"), games.map { it.uid })
assertEquals(listOf("Diablo II: Resurrected" to "OSI", "StarCraft II" to "S2"), games.map { it.name to it.code })
assertFalse(BattleNet.notInstalled(BattleNet.title("osi")!!, listOf("osic")))
assertFalse(BattleNet.notInstalled(BattleNet.title("s2")!!, games.map { it.installUid }))
@Test fun theFolderPicksBetweenTwoDiabloThreeInstalls() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val legacy = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III")
val china = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III China")
legacy.mkdirs()
china.mkdirs()
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "diablo3"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))),
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III China"))))),
))
assertEquals(setOf("diablo3", "d3cn"), BattleNet.games(context).map { it.installUid }.toSet())
val sidecar = StoreGameSidecar(Store.BATTLENET, "diablo3", "Diablo III", "")
val oldGame = InstalledStoreGame(sidecar, legacy)
val chinaGame = InstalledStoreGame(sidecar, china)
val records = listOf(oldGame, chinaGame)
assertEquals(chinaGame, StoresState.pickInstalled(Store.BATTLENET, "diablo3", china, records))
assertEquals(oldGame, StoresState.pickInstalled(Store.BATTLENET, "diablo3", legacy, records))
assertEquals("d3cn", BattleNetInstall.installUid(context, chinaGame))
assertEquals("diablo3", BattleNetInstall.installUid(context, oldGame))
val missing = File(china, "missing")
assertNull(StoresState.pickInstalled(Store.BATTLENET, "diablo3", missing, records))
assertNull(BattleNetInstall.installUid(context, InstalledStoreGame(sidecar, missing)))
}
@Test fun anUnfinishedInstallIsARegistrationButNotAGame() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/StarCraft II").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(
field(1, "s2_cn"), field(2, "s2c"),
field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/StarCraft II"))),
field(4, message(field(1, message(varintField(1, 0), varintField(2, 0))))),
)),
))
assertTrue("an unfinished install is not a library game", BattleNet.games(context).none { it.installUid == "s2_cn" })
assertEquals(listOf("s2_cn"), BattleNet.registrationsAt(context, "s2", folder))
}
@Test fun aChinaCopyLaunchesWithItsRecordedCode() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val legacy = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III").apply { mkdirs() }
val china = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III China").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "diablo3"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))),
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III China"))))),
))
assertEquals("D3CN", BattleNet.launchCode(context, "diablo3", china))
assertEquals("D3CN", BattleNet.launchCode(context, "d3cn", china))
assertEquals(listOf("d3cn"), BattleNet.registrationsAt(context, "d3cn", china))
assertEquals("D3", BattleNet.launchCode(context, "diablo3", legacy))
assertEquals("D3", BattleNet.launchCode(context, "diablo3", null))
assertNull(BattleNet.launchCode(context, "diablo3", File(china, "missing")))
val game = com.droiddeck.launcher.frontend.Library.SteamGame(
1234, "Diablo III", null, com.droiddeck.launcher.frontend.Library.ADDED,
source = Store.BATTLENET.id, storeId = "diablo3", gameFiles = china,
)
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(context, game, null)!!
assertEquals(com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET, command.program)
assertEquals(listOf("launch", "D3CN"), command.args)
}
@Test fun aCopyInAnotherFolderResolvesItsOwnLaunchCode() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val first = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/StarCraft II").apply { mkdirs() }
val second = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/StarCraft II Copy").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "s2_cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/StarCraft II"))))),
field(1, message(field(1, "s2_cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/StarCraft II Copy"))))),
))
// games() keeps one copy per launch code, so the second folder is only reachable per folder.
assertEquals(1, BattleNet.games(context).size)
assertEquals("S2", BattleNet.launchCode(context, "s2", first))
assertEquals("S2", BattleNet.launchCode(context, "s2", second))
}
@Test fun aCopyRegisteredUnderAnotherUidOfTheSameProductStillLaunches() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo IV").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "fen"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo IV"))))),
))
assertTrue(BattleNet.sameTitle("fen", "fenris"))
assertFalse(BattleNet.sameTitle("fen", "wow"))
assertEquals("Fen", BattleNet.launchCode(context, "fenris", folder))
assertEquals("Fen", BattleNet.launchCode(context, "fen", folder))
}
@Test fun aMissingInstallFolderCannotLaunchEvenWhenRegistered() {
val pfx = File(BattleNet.prefix(context), "pfx")
val db = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").apply { parentFile!!.mkdirs() }
val folder = File(pfx, "drive_c/Games/D3")
db.writeBytes(message(field(1, message(field(1, "d3cn"), field(3, message(field(1, "C:/Games/D3")))))))
assertNull(BattleNet.launchCode(context, "diablo3", folder))
assertEquals(true, BattleNet.folderHasRegistrations(context, folder))
}
@Test fun anUnreadableAgentDatabaseDoesNotAuthorizeFolderDeletion() {
val pfx = File(BattleNet.prefix(context), "pfx")
val db = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").apply { parentFile!!.mkdirs() }
val folder = File(pfx, "drive_c/Games/D3").apply { mkdirs() }
db.writeBytes(byteArrayOf(0x0a, 0x7f))
assertFalse(BattleNet.registrationsReadable(context))
assertNull(BattleNet.folderHasRegistrations(context, folder))
}
@Test fun productFallbackResolvesBothLaunchCodeAndManagementUid() {
val pfx = File(BattleNet.prefix(context), "pfx")
val db = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").apply { parentFile!!.mkdirs() }
val folder = File(pfx, "drive_c/Games/WoW").apply { mkdirs() }
db.writeBytes(message(field(1, message(field(1, "wowf_live"), field(2, "wowf"), field(3, message(field(1, "C:/Games/WoW")))))))
assertEquals("WoWF", BattleNet.launchCode(context, "wow_forever", folder))
val sidecar = StoreGameSidecar(Store.BATTLENET, "wow_forever", "World of Warcraft", "")
assertEquals("wowf_live", BattleNetInstall.installUid(context, InstalledStoreGame(sidecar, folder)))
}
@Test fun aRegistrationForAMissingFolderStillCountsAsPreexisting() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III")
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))),
))
assertTrue(BattleNet.games(context).none { it.folder.absolutePath == folder.absolutePath })
assertEquals(listOf("d3cn"), BattleNet.registrationsAt(context, "diablo3", folder))
folder.mkdirs()
val uninstalled = AtomicBoolean(false)
val item = CatalogItem(Store.BATTLENET, "diablo3", "Diablo III", null)
BattleNetInstaller(context, item, folder, false, uninstall = {
uninstalled.set(true)
true
}).cancel(true)
Thread.sleep(100)
assertFalse("a registration whose folder was missing is still pre-existing", uninstalled.get())
}
@Test fun aStaleRegistryRowDoesNotHideAnAgentRegistrationInAnotherFolder() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val a = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III A")
val b = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III B")
File(pfx, "system.reg").writeText("""
WINE REGISTRY Version 2
[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Diablo III] 1
"InstallLocation"="Z:/root/Games/Stores/Battle.net/Diablo III A"
"UninstallString"="\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\" --uid=d3cn"
""".trimIndent())
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III B"))))),
))
assertEquals(emptyList<String>(), BattleNet.registrationsAt(context, "diablo3", a))
assertEquals(listOf("d3cn"), BattleNet.registrationsAt(context, "diablo3", b))
}
@Test fun aPathOnlyAgentRegistrationMakesTheFolderUnknown() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III")
val db = message(field(1, message(field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))))
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(db)
assertEquals("", BattleNet.productDbRegistrations(db)!!.single().uid)
assertNull(BattleNet.registrationsAt(context, "diablo3", folder))
}
@Test fun aPreexistingRegistrationIsNotUninstalled() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "1"),
)
val uninstalled = AtomicBoolean(false)
val installer = BattleNetInstaller(context, item, folder, false, uninstall = {
uninstalled.set(true)
true
}) { listOf("osic") }
installer.cancel(true)
Thread.sleep(100)
assertFalse("a registration that existed before the task must survive", uninstalled.get())
}
@Test fun aCancelledInstallUninstallsOnlyTheRegistrationItCreated() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val seen = AtomicReference<String?>(null)
val done = CountDownLatch(1)
val installer = BattleNetInstaller(context, item, folder, false, cleanupVerifyMs = 0, uninstall = { uid ->
seen.set(uid)
done.countDown()
true
}) { listOf("osic") }
installer.cancel(true)
assertTrue(done.await(5, TimeUnit.SECONDS))
assertEquals("osic", seen.get())
}
@Test fun aCancelledInstallsCleanupHoldsTheFolderForUninstall() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val holding = AtomicBoolean(false)
val done = CountDownLatch(1)
val ownership = Ownership(item)
ownership.createdFolder.set(true)
var registered = true
val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, cleanupVerifyMs = 0, uninstall = { uid ->
holding.set(StoreInstalls.isDiscarding(folder))
registered = false
done.countDown()
true
}) { if (registered) listOf("osic") else emptyList() }
installer.cancel(true)
assertTrue(done.await(5, TimeUnit.SECONDS))
assertTrue("the cleanup must hold the folder against uninstall", holding.get())
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (StoreInstalls.isDiscarding(folder) && System.nanoTime() < until) Thread.sleep(10)
assertFalse(StoreInstalls.isDiscarding(folder))
assertFalse(folder.exists())
}
@Test fun aLateRegistrationReportedWhileTheWorkerStopsIsUsedForCancellation() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(Store.BATTLENET, "osi", "Diablo II: Resurrected", null)
var visible = false
val seen = AtomicReference<String?>(null)
val done = CountDownLatch(1)
val installer = BattleNetInstaller(context, item, folder, false, registrationWaitMs = 1000, cleanupVerifyMs = 0, uninstall = { uid ->
seen.set(uid)
done.countDown()
true
}) {
if (visible) listOf("osic") else emptyList()
}
val started = BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true }
(started.get(installer) as AtomicBoolean).set(true)
val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true }
.get(installer) as CountDownLatch
installer.cancel(true)
visible = true
ended.countDown()
assertTrue(done.await(5, TimeUnit.SECONDS))
assertEquals("osic", seen.get())
}
@Test fun aCancelledInstallRemovesAFolderItCreatedWithoutARegistration() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected")
assertFalse(folder.exists())
folder.mkdirs()
File(folder, "partial.bin").writeBytes(byteArrayOf(1, 2, 3))
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val ownership = Ownership(item)
val uninstalled = AtomicBoolean(false)
val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, registrationWaitMs = 0, uninstall = {
uninstalled.set(true)
false
}) { emptyList() }
ownership.createdFolder.set(true)
BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true }
.set(installer, AtomicBoolean(true))
val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true }
.get(installer) as CountDownLatch
installer.cancel(true)
ended.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (folder.exists() && System.nanoTime() < until) Thread.sleep(10)
assertFalse("a folder this task created must not survive a cancel", folder.exists())
assertFalse(uninstalled.get())
}
@Test fun aCancelledInstallKeepsTheFolderWhileItsRegistrationRemains() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
File(folder, "partial.bin").writeBytes(byteArrayOf(1, 2, 3))
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val installer = BattleNetInstaller(context, item, folder, false, cleanupVerifyMs = 0, uninstall = { true }) {
listOf("osic")
}
BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true }
.set(installer, AtomicBoolean(true))
val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true }
.get(installer) as CountDownLatch
installer.cancel(true)
ended.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(3)
while (BattleNetCleanup.get(context, folder) == null && System.nanoTime() < until) Thread.sleep(10)
assertTrue("the folder must stay while the registration exists", folder.exists())
assertEquals(BattleNetCleanup.PENDING, BattleNetCleanup.get(context, folder)?.state)
}
@Test fun aCancelledInstallDeletesTheFolderOnceItsRegistrationGoes() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
File(folder, "partial.bin").writeBytes(byteArrayOf(1, 2, 3))
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val ownership = Ownership(item)
ownership.createdFolder.set(true)
var registered = true
val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, cleanupVerifyMs = 0, uninstall = {
registered = false
true
}) { if (registered) listOf("osic") else emptyList() }
BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true }
.set(installer, AtomicBoolean(true))
val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true }
.get(installer) as CountDownLatch
installer.cancel(true)
ended.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (folder.exists() && System.nanoTime() < until) Thread.sleep(10)
assertFalse(folder.exists())
assertNull(BattleNetCleanup.get(context, folder))
}
@Test fun reconcileCleansAMarkerAfterItsRegistrationGoes() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III").apply { mkdirs() }
File(folder, "partial.bin").writeBytes(byteArrayOf(1, 2, 3))
val db = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
db.writeBytes(message(
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))),
))
BattleNetCleanup.mark(context, folder, "diablo3", createdFolder = true, state = BattleNetCleanup.PENDING)
BattleNetInstall.reconcileNow(context, uninstall = { uid ->
assertEquals("d3cn", uid)
db.writeBytes(ByteArray(0))
true
}, verifyMs = 0, watchMs = 0)
assertFalse(folder.exists())
assertNull(BattleNetCleanup.get(context, folder))
}
@Test fun aCancellationRecordsItsMarkerBeforeItWaitsForTheWorker() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val installer = BattleNetInstaller(context, item, folder, false, registrationWaitMs = 0, cleanupVerifyMs = 0) {
emptyList()
}
BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true }
.set(installer, AtomicBoolean(true))
val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true }
.get(installer) as CountDownLatch
installer.cancel(true)
assertEquals(BattleNetCleanup.PENDING, BattleNetCleanup.get(context, folder)?.state)
ended.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(2)
while (BattleNetCleanup.get(context, folder)?.state == BattleNetCleanup.PENDING && System.nanoTime() < until) Thread.sleep(10)
}
@Test fun anActiveMarkerCannotOverwriteACancellation() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
BattleNetCleanup.mark(context, folder, "osi", createdFolder = false, state = BattleNetCleanup.PENDING)
BattleNetCleanup.markActive(context, folder, "osi", createdFolder = true)
val pending = BattleNetCleanup.get(context, folder)!!
assertEquals(BattleNetCleanup.PENDING, pending.state)
assertTrue(pending.createdFolder)
}
@Test fun aCleanupMarkerRewrittenForAReplacementHasANewStamp() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
BattleNetCleanup.mark(context, folder, "osi", createdFolder = false, state = BattleNetCleanup.PENDING)
val first = BattleNetCleanup.get(context, folder)!!
BattleNetCleanup.mark(context, folder, "osi", createdFolder = true, state = BattleNetCleanup.PENDING)
val second = BattleNetCleanup.get(context, folder)!!
assertTrue(second.stamp > first.stamp)
}
@Test fun aCleanupMarkerIsRestoredWithoutTheTask() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
BattleNetCleanup.mark(context, folder, "osi", createdFolder = true, state = BattleNetCleanup.PENDING)
val pending = BattleNetCleanup.pending(context).single()
assertEquals(folder.absolutePath, pending.folder.absolutePath)
assertEquals("osi", pending.id)
assertTrue(pending.createdFolder)
assertEquals(BattleNetCleanup.PENDING, pending.state)
BattleNetCleanup.clear(context, folder)
assertTrue(BattleNetCleanup.pending(context).isEmpty())
}
@Test fun aRegistrationSourceFailureMakesOwnershipUnknown() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
.writeBytes(byteArrayOf(0x0a, 0x03, 0x0a, 0x7f, 0x01))
assertNull(BattleNet.registrationsAt(context, "osi", File(LinuxRuntime.rootDir(context), "root/Games/D2R")))
}
@Test fun aWorkerOwnershipSnapshotFailureDoesNotUninstall() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(Store.BATTLENET, "osi", "Diablo II: Resurrected", null)
val ownership = Ownership(item)
val uninstalled = AtomicBoolean(false)
val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, uninstall = {
uninstalled.set(true)
true
}) { null }
runCatching { installer.run(DownloadQueue.JobHandle("battlenet:snapshot-failure", AtomicBoolean(false))) }
assertFalse("a failed read must not become a final ownership decision", ownership.known)
assertTrue(ownership.preexisting)
installer.cancel(true)
Thread.sleep(100)
assertFalse("a failed worker snapshot must disable destructive cleanup", uninstalled.get())
}
@Test fun aFailedRegistrationReadDoesNotUninstall() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val uninstalled = AtomicBoolean(false)
BattleNetInstaller(context, item, folder, false, uninstall = {
uninstalled.set(true)
true
}) { null }.cancel(true)
Thread.sleep(100)
assertFalse("an unreadable registration source must disable destructive cleanup", uninstalled.get())
}
@Test fun aResumedInstallerKeepsTheOwnershipDecision() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(Store.BATTLENET, "osi", "Diablo II: Resurrected", null)
val ownership = Ownership(item)
ownership.known = true
ownership.preexisting = false
val seen = AtomicReference<String?>(null)
val done = CountDownLatch(1)
BattleNetInstaller(context, item, folder, false, ownership = ownership, cleanupVerifyMs = 0, uninstall = { uid ->
seen.set(uid)
done.countDown()
true
}) { listOf("osic") }.cancel(true)
assertTrue(done.await(5, TimeUnit.SECONDS))
assertEquals("osic", seen.get())
}
@Test fun aRestoredPausedInstallUninstallsTheRegistrationItCreated() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val seen = AtomicReference<String?>(null)
val done = CountDownLatch(1)
BattleNetInstaller(context, item, folder, false, cleanupVerifyMs = 0, uninstall = { uid ->
seen.set(uid)
done.countDown()
true
}) { listOf("osic") }.cancel(true)
assertTrue(done.await(5, TimeUnit.SECONDS))
assertEquals("osic", seen.get())
}
@Test fun theTitlePicksBetweenWarcraftFlavorsInOneFolder() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val wow = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/World of Warcraft")
wow.mkdirs()
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "wow"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/World of Warcraft"))))),
field(1, message(field(1, "wow_classic"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/World of Warcraft"))))),
))
val sidecar = StoreGameSidecar(Store.BATTLENET, "wow_classic", "World of Warcraft Classic", "")
assertEquals("wow_classic", BattleNetInstall.installUid(context, InstalledStoreGame(sidecar, wow)))
assertEquals(listOf("wow"), BattleNet.registrationsAt(context, "wow", File(wow, "_retail_")))
assertEquals(listOf("wow_classic"), BattleNet.registrationsAt(context, "wow_classic", File(wow, "_classic_")))
val single = StoreGameSidecar(Store.BATTLENET, "wow", "World of Warcraft", "")
assertNull(BattleNetInstall.installUid(context, InstalledStoreGame(single, File(wow, "missing"))))
}
@Test fun aScannedGamesShortcutReusesTheKeptRankingInsteadOfWalkingItsFolder() {
@@ -918,9 +408,8 @@ class BattleNetTest {
assertEquals("wow_forever", BattleNet.STORE.first { it.code == "WoWF" }.uid)
assertEquals("fenris", BattleNet.STORE.first { it.code == "Fen" }.uid)
assertTrue(BattleNet.STORE.all { it.uid.matches(Regex("[a-z0-9_]{1,32}")) })
val installedUids = listOf("fenris", "diablo3_enus", null)
.mapNotNull { uid -> uid?.let { BattleNet.title(it)?.uid } }.toSet()
val offered = BattleNet.STORE.filterNot { it.uid in installedUids }.map { it.code }
val installed = listOf("fenris", "diablo3_enus", null)
val offered = BattleNet.STORE.filter { BattleNet.notInstalled(it, installed) }.map { it.code }
assertFalse("Fen" in offered || "D3" in offered)
assertTrue("OSI" in offered && "WoWF" in offered)
assertFalse("WoWF" in BattleNet.STORE.filter { BattleNet.notInstalled(it, listOf("wow_forever")) }.map { it.code })
@@ -939,7 +428,7 @@ class BattleNetTest {
assertFalse(noSteam.enabled(context, game))
assertTrue(BattleNet.ensureNoSteam(context))
assertTrue(noSteam.enabled(context, game))
val command = noSteam.command(context, game, shortcut)!!
val command = noSteam.command(game, shortcut)!!
assertEquals(noSteam.BATTLENET, command.program)
assertEquals(listOf("launch", "Fen"), command.args)
GameEnvironmentStore.setGameNoSteam(context, BattleNet.APP_ID.toString(), false)
@@ -114,6 +114,19 @@ class GameStorageTest {
assertFalse(GameStorage.disconnected(app))
}
@Test fun aRawCardPathTheProcessCannotUseFallsBackToItsStoragePath() {
val usable = setOf("/storage/A042-9B16/Games")
assertEquals("/storage/A042-9B16/Games", GameStorage.reachable("/mnt/media_rw/A042-9B16/Games") { it.path in usable })
}
@Test fun aUsableRawPathAndOtherPathsAreKept() {
assertEquals("/mnt/media_rw/A042-9B16/Games", GameStorage.reachable("/mnt/media_rw/A042-9B16/Games") { true })
assertEquals("/mnt/media_rw/0000-0000/Games", GameStorage.reachable("/mnt/media_rw/0000-0000/Games") { false })
assertEquals("/storage/A042-9B16/Games", GameStorage.reachable("/storage/A042-9B16/Games") { false })
val folder = tmp.newFolder("library").path
assertEquals(folder, GameStorage.reachable(folder) { false })
}
@Test fun onlyAVfatMountCountsAsFat32() {
val mounts = """
/dev/fuse /storage/emulated fuse rw 0 0
@@ -55,7 +55,7 @@ class NoSteamLaunchTest {
"/mnt/droiddeck-sd/Games/Epic/Hogwarts Legacy/.droiddeck-launch.bat", "/mnt/droiddeck-sd/Games/Epic/Hogwarts Legacy",
2733369024L, 0L, emptyList(), source = "epic", launchOptions = "-windowed",
)
val added = NoSteamLaunch.command(context, shortcut, game)!!
val added = NoSteamLaunch.command(shortcut, game)!!
assertEquals(NoSteamLaunch.PROTON_RUN, added.program)
assertEquals(
listOf("--app", "2733369024", "--dir", game.guestDir, "--options", "-windowed", "--", game.guestExe),
@@ -63,10 +63,10 @@ class NoSteamLaunchTest {
)
val plain = NoSteamLaunch.addedCommand(AddedGames.Game(game.folder, game.name, game.exe, game.guestExe, game.guestDir, 2733369024L, 0L, emptyList(), source = "gog"))
assertEquals(listOf("--app", "2733369024", "--dir", game.guestDir, "--", game.guestExe), plain.args)
assertNull(NoSteamLaunch.command(context, shortcut, null))
val steam = NoSteamLaunch.command(context, steamGame, null)!!
assertNull(NoSteamLaunch.command(shortcut, null))
val steam = NoSteamLaunch.command(steamGame, null)!!
assertEquals(listOf("--app", "413150"), steam.args)
val epic = NoSteamLaunch.command(context, launcher, null)!!
val epic = NoSteamLaunch.command(launcher, null)!!
assertEquals(NoSteamLaunch.EPIC to listOf("run"), epic.program to epic.args)
}
@@ -86,14 +86,14 @@ class NoSteamLaunchTest {
assertEquals(413150L, NoSteamLaunch.settingsId(routed))
val entry = Library.SteamGame(413150, "Stardew Valley", null, Library.ADDED)
assertEquals(NoSteamLaunch.settingsId(routed).toString(), NoSteamLaunch.scope(entry))
val command = NoSteamLaunch.command(context, entry, routed)!!
val command = NoSteamLaunch.command(entry, routed)!!
assertEquals(NoSteamLaunch.PROTON_RUN to listOf("--app", "413150"), command.program to command.args)
val plain = AddedGames.Game(File("/x/a"), "a", File("/x/a/a.exe"), "/g/a.exe", "/g", 2733369024L, 0L, emptyList())
assertEquals(2733369024L, NoSteamLaunch.settingsId(plain))
}
@Test fun theRunningSessionIsNamedAfterItsGame() {
val command = NoSteamLaunch.command(context, steamGame, null)!!
val command = NoSteamLaunch.command(steamGame, null)!!
assertNull(NoSteamLaunch.nameFor(command.program, command.args))
NoSteamLaunch.remember(command)
assertEquals("Stardew Valley", NoSteamLaunch.nameFor(command.program, command.args))
@@ -21,6 +21,24 @@ class SecondaryLibraryTest {
assertFalse(SecondaryLibrary.privateRoot(files, content).exists())
}
@Test fun aCardReachedThroughItsOtherPathKeepsItsPrivateDirectories() {
val files = tmp.newFolder("files")
val raw = SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/A042-9B16/Games")).apply { mkdirs() }
assertEquals(raw, SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games")))
val storage = SecondaryLibrary.privateRoot(files, File("/storage/B2BD-BCFC/Games")).apply { mkdirs() }
assertEquals(storage, SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/B2BD-BCFC/Games")))
}
@Test fun aLibraryWithItsOwnPrivateDirectoriesKeepsThem() {
val files = tmp.newFolder("files")
val own = SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games")).apply { mkdirs() }
val raw = File(own.parentFile, SecondaryLibrary.privateRoot(tmp.newFolder("other"), File("/mnt/media_rw/A042-9B16/Games")).name)
raw.mkdirs()
assertEquals(own, SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games")))
assertEquals(raw, SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/A042-9B16/Games")))
assertFalse(SecondaryLibrary.privateRoot(files, File("/storage/emulated/0/Games")).exists())
}
@Test fun aWritableAliasIsSelectedAndItsProbeIsRemoved() {
val library = tmp.newFolder("shared")
val candidate = File(tmp.root, "direct")
@@ -28,41 +28,6 @@ class BattleNetInstallTest {
eu|e474008a3535d8ea978949a90d9873e6|db0583272ed15286569b5f24ce516876||119725|16.1.2.119725|f6a454799d25791e5a37a7547d75ce49
""".trimIndent()
private val osiVersions = """
Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16
## seqn = 3964805
us|11111111111111111111111111111111|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa||93847|3.3.93847|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
eu|11111111111111111111111111111111|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa||93847|3.3.93847|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
kr|11111111111111111111111111111111|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa||93847|3.3.93847|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
""".trimIndent()
private val osicVersions = """
Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16
## seqn = 3964866
cn|44444444444444444444444444444444|cccccccccccccccccccccccccccccccc||93854|3.3.93854|dddddddddddddddddddddddddddddddd
""".trimIndent()
private val s2Versions = """
Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16
## seqn = 4064835
us|55555555555555555555555555555555|eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee||98310|5.0.17.98310|ffffffffffffffffffffffffffffffff
cn|66666666666666666666666666666666|eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee||93333|5.0.14.93333|ffffffffffffffffffffffffffffffff
""".trimIndent()
private val s2cVersions = """
Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16
## seqn = 4064962
cn|77777777777777777777777777777777|eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee||98370|5.0.17.98370|ffffffffffffffffffffffffffffffff
""".trimIndent()
private val anbsVersions = """
Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16
## seqn = 4105154
us|88888888888888888888888888888888|99999999999999999999999999999999||3935504|5.1.3.3935504|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab
eu|88888888888888888888888888888888|99999999999999999999999999999999||3935504|5.1.3.3935504|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab
kr|88888888888888888888888888888888|99999999999999999999999999999999||3935504|5.1.3.3935504|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab
""".trimIndent()
@Test fun theActiveRowGivesTheRegionAndBuildOnDisk() {
assertEquals("us" to "e474008a3535d8ea978949a90d9873e6", BattleNetInstall.buildKey(buildInfo))
assertNull(BattleNetInstall.buildKey("Branch!STRING:0|Active!DEC:1\n"))
@@ -76,18 +41,9 @@ class BattleNetInstallTest {
assertNull(BattleNetInstall.latestBuild("", "us"))
}
@Test fun theChinaProductsAreNotOnTheGlobalVersionLine() {
assertNull(BattleNetInstall.latestBuild(osiVersions, "cn"))
assertEquals("44444444444444444444444444444444", BattleNetInstall.latestBuild(osicVersions, "cn"))
assertEquals("66666666666666666666666666666666", BattleNetInstall.latestBuild(s2Versions, "cn"))
assertEquals("77777777777777777777777777777777", BattleNetInstall.latestBuild(s2cVersions, "cn"))
assertNull(BattleNetInstall.latestBuild(anbsVersions, "cn"))
}
@Test fun theVersionServiceIsBlizzardsChineseOneForChina() {
assertEquals("https://us.version.battle.net/v2/products/wow/versions", BattleNetInstall.versionsUrl("us", "wow"))
assertEquals("https://cn.version.battlenet.com.cn/v2/products/d3cn/versions", BattleNetInstall.versionsUrl("cn", "d3cn"))
assertEquals("https://cn.version.battlenet.com.cn/v2/products/s2c/versions", BattleNetInstall.versionsUrl("cn", "s2c"))
}
@Test fun theDeviceLanguagePicksABlizzardLocale() {
@@ -113,16 +69,7 @@ class BattleNetInstallTest {
assertTrue(BattleNetInstall.headless(CatalogItem(Store.BATTLENET, "gryphon", "Warcraft Rumble", null)))
assertEquals("hsb", BattleNetInstall.product("hs_beta"))
assertEquals("d3", BattleNetInstall.product("diablo3_enus"))
assertEquals("d3cn", BattleNetInstall.product("d3cn"))
assertEquals("osic", BattleNetInstall.product("osic"))
assertEquals("s2c", BattleNetInstall.product("s2_cn"))
assertEquals("anbs", BattleNetInstall.product("anbs_cn"))
assertEquals("osic", BattleNetInstall.chinaProduct("osi"))
assertEquals("s2c", BattleNetInstall.chinaProduct("s2"))
assertEquals("d3cn", BattleNetInstall.chinaProduct("diablo3"))
assertNull(BattleNetInstall.chinaProduct("anbs"))
assertNull(BattleNetInstall.chinaProduct("wow"))
assertTrue(BattleNetInstall.headless(CatalogItem(Store.BATTLENET, "d3cn", "Diablo III", null)))
assertFalse(BattleNetInstall.headless(CatalogItem(Store.BATTLENET, "d3cn", "Diablo III", null)))
assertFalse(BattleNetInstall.headless(CatalogItem(Store.EPIC, "gryphon", "Warcraft Rumble", null)))
}
@@ -131,76 +78,12 @@ class BattleNetInstallTest {
try {
BattleNetInstall.check("gryphon", folder, false)
BattleNetInstall.checks.submit {}.get()
assertFalse(synchronized(BattleNetInstall.checkedAt) {
BattleNetInstall.updateKey("gryphon", folder) in BattleNetInstall.checkedAt
})
assertFalse(synchronized(BattleNetInstall.checkedAt) { "gryphon" in BattleNetInstall.checkedAt })
} finally {
folder.deleteRecursively()
}
}
@Test fun aBuildThatChangesDuringTheCheckIsAskedAgainOnlyTwice() {
val folder = Files.createTempDirectory("bnet-retry").toFile()
val scheduled = mutableListOf<Pair<() -> Unit, Long>>()
val originalFetch = BattleNetInstall.fetchVersions
val originalSchedule = BattleNetInstall.scheduleRecheck
try {
File(folder, ".build.info").writeText(buildInfo)
var asked = 0
BattleNetInstall.fetchVersions = {
// Every request runs against a different build, so the post-read never matches.
asked += 1
File(folder, ".build.info").writeText(buildInfo.replace("e474008a3535d8ea978949a90d9873e6", "%032x".format(asked)))
versions
}
BattleNetInstall.scheduleRecheck = { body, delay -> scheduled += body to delay }
synchronized(BattleNetInstall.checkedAt) { BattleNetInstall.checkedAt.clear() }
BattleNetInstall.check("gryphon", folder, false)
BattleNetInstall.checks.submit {}.get()
assertEquals(1, scheduled.size)
assertEquals(30_000L, scheduled[0].second)
scheduled[0].first()
BattleNetInstall.checks.submit {}.get()
assertEquals(2, scheduled.size)
assertEquals(60_000L, scheduled[1].second)
var next = 1
repeat(4) {
if (next < scheduled.size) {
scheduled[next].first()
BattleNetInstall.checks.submit {}.get()
next += 1
}
}
assertEquals("re-checks are bounded", 2, scheduled.size)
assertEquals(30_000L, scheduled[0].second)
assertNull(BattleNetInstall.updates[BattleNetInstall.updateKey("gryphon", folder)])
} finally {
BattleNetInstall.fetchVersions = originalFetch
BattleNetInstall.scheduleRecheck = originalSchedule
synchronized(BattleNetInstall.checkedAt) { BattleNetInstall.checkedAt.remove(BattleNetInstall.updateKey("gryphon", folder)) }
folder.deleteRecursively()
}
}
@Test fun updateStateIsSeparateForEachInstallFolder() {
val one = Files.createTempDirectory("bnet-one").toFile()
val two = Files.createTempDirectory("bnet-two").toFile()
try {
val first = BattleNetInstall.updateKey("diablo3", one)
val second = BattleNetInstall.updateKey("diablo3", two)
assertFalse(first == second)
BattleNetInstall.updates[first] = true
assertNull(BattleNetInstall.updates[second])
BattleNetInstall.updates.remove(first)
} finally {
one.deleteRecursively()
two.deleteRecursively()
}
}
@Test fun theAgentStatusPicksTheDownloadStep() {
assertEquals(BattleNetInstall.Step.PREPARING, BattleNetInstall.step(1008, 0, 0, 0))
assertEquals(BattleNetInstall.Step.PREPARING, BattleNetInstall.step(1003, 500, 0, 0))
@@ -0,0 +1,34 @@
package com.droiddeck.launcher.stores.battlenet
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class BattleNetLibraryTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@Test fun aMissingLibraryLeavesBattleNetsInstallFolderAlone() {
SessionPrefs.setGameStorage(app, "/storage/0000-0000/Games", "SD card")
assertTrue(BattleNetClient.library(app).isEmpty())
}
@Test fun anAttachedLibraryIsHandedToBattleNet() {
SessionPrefs.setGameStorage(app, tmp.newFolder("card").path, "SD card")
assertEquals("--library", BattleNetClient.library(app).firstOrNull())
}
@Test fun internalStorageIsHandedToBattleNetWhenItIsTheChoice() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
assertEquals("--library", BattleNetClient.library(app).firstOrNull())
}
}
@@ -1,11 +1,8 @@
package com.droiddeck.launcher.stores.download
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.*
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
import com.droiddeck.launcher.stores.battlenet.BattleNetInstaller
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@@ -15,11 +12,9 @@ import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.json.JSONArray
import org.json.JSONObject
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowLooper
import org.robolectric.shadows.ShadowStatFs
@RunWith(RobolectricTestRunner::class)
@@ -122,351 +117,6 @@ class DownloadQueueRetryTest {
assertNull(DownloadQueue.entry(entry.key))
}
@Test fun cancellingBeforeTheJobIsPublishedCancelsIt() {
val entry = DownloadEntry(Store.GOG, "cancel-before-publish", "Cancel before publish")
val factoryEntered = CountDownLatch(1)
val release = CountDownLatch(1)
val cancelled = CountDownLatch(1)
val job = object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {
if (deleteFiles) cancelled.countDown()
}
}
DownloadQueue.enqueue(app, entry) {
factoryEntered.countDown()
release.await(5, TimeUnit.SECONDS)
job
}
assertTrue(factoryEntered.await(5, TimeUnit.SECONDS))
DownloadQueue.pause(entry.key)
DownloadQueue.cancel(app, entry.key)
release.countDown()
assertTrue("cancel must reach the job published after the request", cancelled.await(5, TimeUnit.SECONDS))
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.state != DownloadState.CANCELLED && System.nanoTime() < until) {
Thread.sleep(10)
}
assertEquals(DownloadState.CANCELLED, DownloadQueue.entry(entry.key)?.state)
DownloadQueue.clear(app, entry.key)
}
@Test fun aRejectedEnqueueDoesNotRunItsAcceptedCallback() {
val entry = DownloadEntry(
Store.BATTLENET, "rejected-enqueue", "Rejected enqueue",
cleanupKey = "${Store.BATTLENET.id}:rejected-enqueue",
)
val started = CountDownLatch(1)
val release = CountDownLatch(1)
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
started.countDown()
release.await()
return null
}
override fun cancel(deleteFiles: Boolean) {}
}
}
assertTrue(started.await(5, TimeUnit.SECONDS))
var accepted = false
assertFalse(DownloadQueue.enqueue(app, entry, onAccepted = { accepted = true }) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {}
}
})
assertFalse(accepted)
release.countDown()
DownloadQueue.clear(app, entry.key)
}
@Test fun aSavedQueueRestoreCarriesOwnershipIntoEnqueue() {
val root = File(app.filesDir, "restore-root").apply { mkdirs() }
val key = "battlenet:restore-chain"
SavedQueue.resetForTest()
SavedQueue.remember(
app,
CatalogItem(
Store.BATTLENET, "restore-chain", "Restore chain", null,
extra = mapOf("preexisting" to "0"),
),
root,
)
val row = JSONObject().apply {
put("paused", true)
put("root", root.absolutePath)
put("item", JSONObject().apply {
put("store", Store.BATTLENET.id); put("id", "restore-chain"); put("title", "Restore chain")
put("extra", JSONObject().put("preexisting", "0"))
put("owned", true)
})
}
File(app.filesDir, "store-queue.json").writeText(JSONArray().put(row).toString())
DownloadQueue.holdPaused(key)
val previous = StoresState.backend(Store.BATTLENET)
val installed = CountDownLatch(1)
StoresState.register(object : StoreBackend {
override val store = Store.BATTLENET
override fun signIn(context: Context) {}
override fun signOut(context: Context) {}
override fun syncLibrary(context: Context, force: Boolean) {}
override fun loadShelves(context: Context, force: Boolean) {}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
override fun install(context: Context, item: CatalogItem, root: File) {
BattleNetInstall.enqueue(context, item, StoreInstallRoot.folderFor(context, store, item.id, item.title, root))
installed.countDown()
}
})
try {
SavedQueue.restore(app)
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (installed.count > 0 && System.nanoTime() < until) {
ShadowLooper.idleMainLooper()
Thread.sleep(10)
}
assertTrue(installed.await(1, TimeUnit.SECONDS))
assertEquals("0", SavedQueue.remembered(key)?.extra?.get("preexisting"))
DownloadQueue.clear(app, key)
} finally {
if (previous != null) StoresState.register(previous)
SavedQueue.resetForTest()
File(app.filesDir, "store-queue.json").delete()
}
}
@Test fun aRejectedUpdateKeepsTheSavedOwnershipSnapshot() {
val original = CatalogItem(
Store.BATTLENET, "rejected-update", "Rejected update", null,
extra = mapOf("preexisting" to "0"),
)
SavedQueue.remember(app, original, null)
val entry = DownloadEntry(Store.BATTLENET, "rejected-update", "Rejected update")
val started = CountDownLatch(1)
val release = CountDownLatch(1)
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
started.countDown()
release.await()
return null
}
override fun cancel(deleteFiles: Boolean) {}
}
}
assertTrue(started.await(5, TimeUnit.SECONDS))
var accepted = false
assertFalse(DownloadQueue.enqueue(app, entry, onAccepted = {
accepted = true
SavedQueue.remember(app, original.copy(extra = mapOf("preexisting" to "1")), null)
}) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {}
}
})
assertFalse(accepted)
assertEquals("0", SavedQueue.remembered(entry.key)?.extra?.get("preexisting"))
release.countDown()
DownloadQueue.clear(app, entry.key)
}
@Test fun aFactorylessFailedBattleNetEntryDoesNotBlockAReplacement() {
val entry = DownloadEntry(
Store.BATTLENET, "factoryless-failure", "Factoryless failure",
cleanupKey = "${Store.BATTLENET.id}:factoryless-failure",
)
DownloadQueue.recordFailed(app, entry, "failed before a job existed")
DownloadQueue.clear(app, entry.key)
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {}
}
}
assertNotNull("a cleared factoryless failure must not hold a cleanup key", DownloadQueue.entry(entry.key))
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.isActive == true && System.nanoTime() < until) Thread.sleep(10)
DownloadQueue.clear(app, entry.key)
}
@Test fun aBattleNetClientDownloadIsNotInTheGameCleanupGuard() {
val entry = DownloadEntry(Store.BATTLENET, "battlenet-client", "Battle.net")
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {}
}
}
DownloadQueue.cancel(app, entry.key)
assertFalse(DownloadQueue.isCancelling(entry.key))
DownloadQueue.clear(app, entry.key)
}
@Test fun aPauseCallbackDoesNotReleaseAnotherCleanup() {
val title = "Pause during cleanup"
val entry = DownloadEntry(
Store.BATTLENET, "pause-during-cleanup", title,
cleanupKey = "${Store.BATTLENET.id}:pause-during-cleanup",
)
val cancelled = CountDownLatch(1)
val release = CountDownLatch(1)
val job = object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {
if (!deleteFiles) return
cancelled.countDown()
Thread({
release.await()
DownloadQueue.cleanupFinished(entry.key)
}, "test-pause-cleanup").start()
}
}
DownloadQueue.enqueue(app, entry) { job }
DownloadQueue.cancel(app, entry.key)
assertTrue(cancelled.await(5, TimeUnit.SECONDS))
assertTrue(DownloadQueue.isCancelling(entry.key))
val folder = File(LinuxRuntime.rootDir(app), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(Store.BATTLENET, entry.id, title, null)
BattleNetInstaller(app, item, folder, false).cancel(false)
assertTrue("a pause must not release the destructive cleanup guard", DownloadQueue.isCancelling(entry.key))
release.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.isCancelling(entry.key) && System.nanoTime() < until) Thread.sleep(10)
assertFalse(DownloadQueue.isCancelling(entry.key))
val entryUntil = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.state != DownloadState.CANCELLED && System.nanoTime() < entryUntil) {
Thread.sleep(10)
}
DownloadQueue.clear(app, entry.key)
}
@Test fun aDoubleClearStartsOneCleanup() {
val entry = DownloadEntry(
Store.BATTLENET, "double-clear", "Double clear",
cleanupKey = "${Store.BATTLENET.id}:double-clear",
)
val cancelled = CountDownLatch(1)
val release = CountDownLatch(1)
val cancels = AtomicInteger()
val job = object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {
if (!deleteFiles) return
cancels.incrementAndGet()
cancelled.countDown()
Thread({
release.await()
DownloadQueue.cleanupFinished(entry.key)
}, "test-double-clear").start()
}
}
DownloadQueue.enqueue(app, entry) { job }
val failedUntil = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.state != DownloadState.FAILED && System.nanoTime() < failedUntil) {
Thread.sleep(10)
}
DownloadQueue.clear(app, entry.key)
DownloadQueue.clear(app, entry.key)
assertTrue(cancelled.await(5, TimeUnit.SECONDS))
assertEquals(1, cancels.get())
assertTrue(DownloadQueue.isCancelling(entry.key))
release.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.isCancelling(entry.key) && System.nanoTime() < until) Thread.sleep(10)
assertFalse(DownloadQueue.isCancelling(entry.key))
}
@Test fun aCancelledBattleNetJobBlocksAReplacementWhileCleanupRuns() {
val entry = DownloadEntry(
Store.BATTLENET, "same-folder-race", "Same folder race",
cleanupKey = "${Store.BATTLENET.id}:same-folder-race",
)
val started = CountDownLatch(1)
val cancelled = CountDownLatch(1)
val release = CountDownLatch(1)
val cancels = AtomicInteger()
val job = object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
started.countDown()
return null
}
override fun cancel(deleteFiles: Boolean) {
if (!deleteFiles) return
cancels.incrementAndGet()
cancelled.countDown()
Thread({
release.await()
DownloadQueue.cleanupFinished(entry.key)
}, "test-cleanup").start()
}
}
DownloadQueue.enqueue(app, entry) { job }
assertTrue(started.await(5, TimeUnit.SECONDS))
try {
DownloadQueue.cancel(app, entry.key)
DownloadQueue.cancel(app, entry.key)
assertTrue(cancelled.await(5, TimeUnit.SECONDS))
assertEquals(1, cancels.get())
assertTrue(DownloadQueue.isCancelling(entry.key))
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.state != DownloadState.CANCELLED && System.nanoTime() < until) {
Thread.sleep(10)
}
assertEquals(DownloadState.CANCELLED, DownloadQueue.entry(entry.key)?.state)
DownloadQueue.clear(app, entry.key)
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = "replacement"
override fun cancel(deleteFiles: Boolean) {}
}
}
assertNull("replacement must not be published during cleanup", DownloadQueue.entry(entry.key))
} finally {
release.countDown()
}
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.isCancelling(entry.key) && System.nanoTime() < until) Thread.sleep(10)
assertFalse(DownloadQueue.isCancelling(entry.key))
}
@Test fun aCancelledBattleNetJobHoldsRemovalUntilItsCleanupFinishes() {
val entry = DownloadEntry(
Store.BATTLENET, "hold-during-cleanup", "Hold during cleanup",
cleanupKey = "${Store.BATTLENET.id}:hold-during-cleanup",
)
val cancelled = CountDownLatch(1)
val release = CountDownLatch(1)
val job = object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {
if (!deleteFiles) return
cancelled.countDown()
Thread({
release.await(5, TimeUnit.SECONDS)
DownloadQueue.cleanupFinished(entry.key)
}, "test-hold-cleanup").start()
}
}
DownloadQueue.enqueue(app, entry) { job }
val failed = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.state != DownloadState.FAILED && System.nanoTime() < failed) Thread.sleep(10)
DownloadQueue.cancel(app, entry.key)
assertTrue(cancelled.await(5, TimeUnit.SECONDS))
assertFalse(DownloadQueue.holdForRemoval(entry.key))
val held = CountDownLatch(1)
Thread({
if (DownloadQueue.stopForRemoval(app, entry.key)) held.countDown()
}, "test-hold-removal").start()
assertFalse("removal must wait for the cancellation cleanup", held.await(300, TimeUnit.MILLISECONDS))
release.countDown()
assertTrue(held.await(5, TimeUnit.SECONDS))
DownloadQueue.releaseRemoval(entry.key)
}
@Test fun heldPausedBackendRestoresAndResumesWithoutAPlaceholder() {
val entry = DownloadEntry(Store.GOG, "restored-paused", "Paused")
val ran = CountDownLatch(1)
-170
View File
@@ -1,170 +0,0 @@
# Battle.net China install, update and cleanup mapping
Last reviewed: 2026-11-16, against `main` `a20528c` with this change applied. The China
version rows were observed on 2026-11-06 at
`cn.version.battlenet.com.cn/v2/products/<product>/versions`; installs use
`cn.patch.battlenet.com.cn`. #1660 added the China uid aliases to the catalogue and #1661
made the Agent driver report Battle.net's own refusal reason instead of `exit 0`; #1705 was
closed in favour of this change. This document describes the merged state and supersedes the
earlier plan that treated #1705 as pending.
## Product mapping
| Game | Store uid | China uid | China product | China version | Handling |
|---|---|---|---|---|---|
| World of Warcraft | `wow` | same uid | `wow` | 12.1.5.70783 | none |
| World of Warcraft Classic | `wow_classic` | same uid | `wow_classic` | 5.5.4.70631 | none |
| World of Warcraft Classic Era | `wow_classic_era` | same uid | `wow_classic_era` | 1.15.9.70576 | none |
| World of Warcraft Classic Anniversary | `wow_classic_anniversary` | same uid | `wow_anniversary` | 2.5.6.70577 | none |
| World of Warcraft: Forever | `wow_forever` | same uid, or unknown uid with product `wowf` | `wowf` | 1.60.1.70790 | in `TITLES`, excluded from `STORE` |
| Diablo III | `diablo3` | `d3cn` | `d3cn` | 2.8.1.101167 | alias; install and update use `d3cn` |
| Diablo II: Resurrected | `osi` | `osic` | `osic` | 3.3.93854 | alias; install and update use `osic` |
| StarCraft II | `s2` | `s2_cn` | `s2c` | 5.0.17.98370 | alias; install maps uid to `s2_cn` and product to `s2c` |
| Diablo Immortal | `anbs` | `anbs_cn` | `anbs` | no `cn` row | uid alias only; unverified |
| Hearthstone | `hs_beta` | same uid | `hsb` | 37.0.2.256589.255790 | none |
| Heroes of the Storm | `heroes` | same uid | `hero` | 2.55.3.89566 | none |
| Overwatch 2 | `prometheus` | same uid | `pro` | 2.25.1.0.155284N | none |
| StarCraft: Remastered | `s1` | same uid | `s1` | 1.23.10.11269 | none |
| Warcraft III: Reforged | `w3` | same uid | `w3` | no `cn` row | none |
| `wow_classic_titan` | not in the catalogue | unconfirmed | `wow_classic_titan` | not checked | out of scope |
No separate China uid has been observed for `wow`, the Classic flavors, `hs_beta`,
`heroes`, `prometheus`, `s1` or `w3`; the client reports the store uid for those.
## What the change does
### Catalogue
`BattleNet.CN_UIDS` maps the China uids to the existing cards instead of adding titles of
their own:
- `d3cn` resolves to the `diablo3` card with launch code `D3CN` and product `d3cn`. The
standalone `d3cn` title and the `STORE`/`fetchCovers` filters for it are gone.
- `osic` resolves to `osi` with product `osic`; `s2_cn` resolves to `s2` with product
`s2c`; `anbs_cn` resolves to `anbs` with product `anbs`.
- Locale suffixes resolve through the base alias, so `osic_zhcn` and `s2_cn_zhcn` name the
same cards.
A `BattleNet.Game` keeps the store uid in `uid` and the Agent's uid in `installUid`. The
Library, the desktop shortcut, the store "installed" state, covers and the launch code
therefore agree; a China Diablo III install still lands on the `diablo3` card and launches
with `D3CN`.
### Install driver
On a China agent (`region == "cn"`) every install sends `account_country = CHN` and
`geo_ip_country = CN`, not only the remapped products. Products `osi`, `s2` and `diablo3`
become `osic`, `s2c` and `d3cn`; uids become `osic`, `s2_cn` and `d3cn` (`anbs` becomes
`anbs_cn`). Updates and uninstalls use the uid the Agent recorded, so they are not
remapped.
### Update checks
`BattleNetInstall.check()` reads `.build.info`. When its active branch is `cn`, the version
query uses the China product (`osic`, `s2c`, `d3cn`); other branches keep the store
product. `checkedAt` and `updates` are keyed by `id@folder` (`updateKey`), so an
international and a China copy of Diablo III neither suppress nor offer each other's
update. `anbs` has no China product mapping, so its China check still asks `anbs`, which
has no `cn` row.
### Install identity
Update and uninstall select the installed record by its exact folder and use the Agent uid
recorded for that folder. A folder with no matching registration is not retargeted to
another copy; a game detail opened from a shortcut passes its folder through, so two
Diablo III installs, or WoW flavors sharing one folder, do not act on each other.
### Cancellation ownership
Before an install starts, a raw `product.db` and `system.reg` query records whether the
target folder already has a registration. The query does not require the folder to exist
and does not deduplicate by launch code. The result is `PREEXISTING = pending | 0 | 1`; the
installer worker resolves it once, persists it through `SavedQueue`, and a shared
`Ownership` holder keeps the decision across pause and resume. `SavedQueue` only receives
the item after `DownloadQueue.enqueue()` accepts it (`onAccepted`), so a rejected enqueue
cannot leave ownership for a task that will not run.
Cancel uninstalls only a registration that appeared after the task recorded "no
registration"; a pre-existing registration is never removed. If either registration source
cannot be read, the decision stays conservative (no destructive cleanup) and is not
persisted as final. Cleanup is skipped when the worker has not stopped after the wait.
`clear()` and `cancel()` share one cleanup claim, and a new enqueue for the same game is
rejected while that cleanup runs.
## Why the version lines differ
| Product | Observed rows | Build | Note |
|---|---|---|---|
| `osi` | `us`, `eu`, `kr` | 3.3.93847 | no `cn` row |
| `osic` | `cn` | 3.3.93854 | China only |
| `s2` | `cn` | 5.0.14.93333 | older China line |
| `s2c` | `cn` | 5.0.17.98370 | current China line |
| `d3` | `us`, `eu`, `kr`, `tw` | 2.8.0.99920 | no `cn` row |
| `d3cn` | `cn` | 2.8.1.101167 | China only |
| `anbs` | no `cn` row | - | no separate `anbs_cn` product |
| `w3` | no `cn` row | - | keeps the global build |
### Products without a `cn` row
`osi`, `d3`, `anbs` and `w3` have no `cn` row, and `anbs_cn` has no product or repository
of its own. For `osi` and `d3`, an install made with the store product in a clean folder
misses the China line and the Agent falls back to the international build: for Diablo II:
Resurrected that is 3.3.93847 instead of the China 3.3.93854. The install succeeds, but
`.build.info` and `product.db` now follow the international line, and the BuildConfig
differs, so renaming the folder cannot migrate it. `w3` has no China line at all and keeps
the global build; `anbs` is unverified (see below).
### The two sides then disagree
When the wrong product is installed, `product.db` records `osi` while the China client
enumerates `osic`. DroidDeck shows the game as installed, the client shows it as missing,
and update, repair and uninstall each follow a different product. No error is reported,
which makes this state harder to notice than a visible failure. `s2` is the milder variant:
it does have a `cn` row, but that row is the older 5.0.14.93333 line, while `s2c` is the
current 5.0.17.98370.
### Error 800
Error 800 is not only a China-copy conflict. A folder registered in `product.db`, an empty
directory, a directory with residual files from an earlier attempt, or a path earlier
registered by a different product can trigger it. This change does not alter those triggers
and does not clean them automatically; #1661 now surfaces Battle.net's own refusal reason,
so the failure is reported instead of looking like `exit 0`.
## Automated coverage
- `BattleNetTest`: China uid aliases including locale suffixes, the `d3cn` alias on the
`diablo3` card, folder selection between two Diablo III installs, WoW flavors in one folder,
registrations for a missing folder, pre-existing registration protection,
created-registration cleanup, registration read failure, restored ownership, per-folder
update state, and the cancelled install's folder hold against uninstall.
- `BattleNetInstallTest`: `chinaProduct()`, the `s2c` version URL, the `osic`, `s2c` and
`anbs` version rows, and per-folder update keys.
- `DownloadQueueRetryTest`: double `clear()` single-flight, a rejected enqueue not running
its accepted callback, a rejected update preserving the saved ownership snapshot,
factoryless cleanup, client-download exclusion, a removal hold waiting for a cancelled
Battle.net cleanup, and the restore, install, enqueue chain.
- `tools/tests/test_battlenet.py`: the driver's China uid and product maps, the
install-only condition, and the `CHN`/`CN` request fields.
## Not covered
- Migration of existing wrong-product installs (`osi`, `d3`, `s2`): uninstall through
DroidDeck (it calls the Agent with the uid recorded for the folder) and install again;
renaming or deleting the folder alone leaves the `product.db` registration behind and can
hit 800 on the next attempt.
- Automatic cleanup of the wider 800 triggers; #1661 surfaces the reason, it does not
remove the registration or the folder.
- Diablo Immortal: `anbs` has no `cn` row and `anbs_cn` has no separate product, so whether
the Agent falls back to the international build and whether the client accepts `anbs_cn`
is unverified. This change does not claim to fix it.
- Store region filtering: the store is a static global catalogue and there is no separate
China "owned" feed.
- WoW Classic family cards and deduplication: `STORE` keeps one `WoWC` card and the game
list keeps one folder per launch code. This is an existing design, not a China uid issue.
- `wow_forever` (in `TITLES`, excluded from `STORE`) and `wow_classic_titan` (not in
`TITLES`) catalogue entries.
- Covers for titles without a Steam app id still depend on `us.shop.battle.net`.
- The Battle.net client installer's region; it is pinned to `downloader.battle.net`.
Refs: #1660, #1661, #1705 (closed).
@@ -135,9 +135,6 @@ function job(text) {
return /"state"\s*:\s*\d+/.test(bare) || /"download_current"\s*:/.test(bare);
}
var CHINA = {osi: "osic", s2: "s2_cn", anbs: "anbs_cn", diablo3: "d3cn"};
var CHINA_PRODUCT = {osi: "osic", s2: "s2c", diablo3: "d3cn"};
function install() {
// Blizzard's China repository moved to cn.patch.battlenet.com.cn; cn.patch.battle.net only redirects away from it.
var patch = zone == "cn" ? "cn.patch.battlenet.com.cn" : zone + ".patch.battle.net";
@@ -196,17 +193,6 @@ try {
token = field(agent, "authorization");
zone = field(agent, "region") || "us";
if (!token) throw new Error("no authorization from the agent");
// The China client installs these under uids of its own. s2_cn is served from s2c; anbs_cn shares anbs.
if (zone == "cn" && action == "install") {
country = "CHN";
region = "CN";
if (CHINA[uid]) {
product = CHINA_PRODUCT[uid] || product;
uid = CHINA[uid];
}
}
// The app cancels an install by the uid the Agent really used; report the remapped one.
save(".uid", uid);
if (action == "install") install(); else if (action == "update") update(); else uninstall();
} catch (e) {
save(".error", e.message || "the agent stopped answering");
@@ -1515,17 +1501,6 @@ def read_status(path):
return None
def read_text(path):
try:
with open(path, "rb") as f:
data = f.read()
except OSError:
return None
if data[:2] in (b"\xff\xfe", b"\xfe\xff"):
return data.decode("utf-16", "replace").strip()
return data.decode("utf-8", "replace").strip()
def summary(status):
out = {key: status[key] for key in REPORTED if key in status}
for key in ("download_current", "download_total"):
@@ -1578,7 +1553,7 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
emit("STATE", "starting")
base = os.path.join(CACHE, "agent-%s" % uid)
os.makedirs(CACHE, exist_ok=True)
for suffix in (".json", ".game", ".form", ".error", ".uid"):
for suffix in (".json", ".game", ".form", ".error"):
try:
os.unlink(base + suffix)
except OSError:
@@ -1596,15 +1571,10 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
return 1
seen = None
mark = None
effective = None
moved = time.monotonic()
stalled = False
while True:
done = child.poll() is not None
if effective is None:
effective = read_text(base + ".uid")
if effective:
emit("UID", effective)
status = read_status(base + ".json")
if status is not None and action != "uninstall":
brief = summary(status)
@@ -1650,13 +1620,8 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
if reason is None and action != "uninstall" and game.get("installed") is True \
and (game.get("playable") is True or status.get("state") == DONE_STATE):
binary = ((game.get("binaries") or {}).get("game") or {}).get("relative_path", "")
if effective is None:
effective = read_text(base + ".uid")
result = {"install_dir": game.get("install_dir", windows), "exe": binary,
"version": game.get("local_version", "")}
if effective:
result["uid"] = effective
emit("DONE", json.dumps(result, sort_keys=True))
emit("DONE", json.dumps({"install_dir": game.get("install_dir", windows), "exe": binary,
"version": game.get("local_version", "")}, sort_keys=True))
say("%s %s in %s" % (uid, "updated" if action == "update" else "installed", game.get("install_dir", windows)))
return 0
if reason is None and action == "uninstall" and (game.get("installed") is False or answer == {}):
-46
View File
@@ -1493,19 +1493,6 @@ class AgentTest(Temp):
self.assertIn('var patch = zone == "cn" ? "cn.patch.battlenet.com.cn" : zone + ".patch.battle.net";', script)
self.assertIn("+ patch + ':1119/'", script)
def test_the_driver_installs_chinas_products_under_their_own_uids(self):
script = BNET["AGENT_SCRIPT"]
self.assertIn('var CHINA = {osi: "osic", s2: "s2_cn", anbs: "anbs_cn", diablo3: "d3cn"};', script)
self.assertIn('var CHINA_PRODUCT = {osi: "osic", s2: "s2c", diablo3: "d3cn"};', script)
self.assertIn('if (zone == "cn" && action == "install") {', script)
self.assertIn('country = "CHN";', script)
self.assertIn('region = "CN";', script)
def test_the_driver_reports_the_uid_the_agent_really_uses(self):
script = BNET["AGENT_SCRIPT"]
self.assertIn(' save(".uid", uid);', script)
self.assertLess(script.index('save(".uid", uid);'), script.index('if (action == "install") install();'))
class AgentJobTest(Harness):
def setUp(self):
@@ -1560,39 +1547,6 @@ class AgentJobTest(Harness):
self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"])
self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"})
def test_the_uid_the_agent_installed_under_is_reported(self):
self.install()
folder = str(self.tmp / "Games/Battle.net/Diablo III")
self.files = {
".json": json.dumps({"progress": 1.0, "download_complete": True, "state": 1004}),
".game": json.dumps({"installed": True, "playable": True, "install_dir": "Z:" + folder, "local_version": "2.8.1",
"binaries": {"game": {"relative_path": "Diablo III.exe"}}}),
".uid": "d3cn",
}
self.assertEqual(BNET["agent_job"](self.root, "install", "diablo3", "d3cn", folder, "enUS", "CHN", "CN", poll=0), 0)
self.assertIn(("UID", "d3cn"), self.lines)
self.assertEqual(self.lines[-1][0], "DONE")
self.assertEqual(json.loads(self.lines[-1][1])["uid"], "d3cn")
def test_a_job_that_never_reported_its_uid_reports_none(self):
self.install()
folder = str(self.tmp / "Games/Battle.net/Warcraft Rumble")
self.files = {
".json": json.dumps({"progress": 1.0, "download_complete": True, "state": 1004}),
".game": json.dumps({"installed": True, "playable": True, "install_dir": "Z:" + folder, "local_version": "1"}),
}
self.assertEqual(BNET["agent_job"](self.root, "install", "gryphon", "gryphon", folder, "enUS", "USA", "US", poll=0), 0)
self.assertNotIn("UID", [kind for kind, _ in self.lines])
self.assertNotIn("uid", json.loads(self.lines[-1][1]))
def test_a_job_file_is_read_as_text_in_either_encoding(self):
path = self.tmp / "uid"
path.write_bytes("d3cn".encode("utf-16"))
self.assertEqual(BNET["read_text"](str(path)), "d3cn")
path.write_bytes(b"d3cn")
self.assertEqual(BNET["read_text"](str(path)), "d3cn")
self.assertIsNone(BNET["read_text"](str(self.tmp / "missing")))
def test_an_install_on_another_volume_is_handed_over_by_its_drive_once_the_prefix_is_stopped(self):
self.install()
card = self.tmp / "card"