mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
fix(battlenet): a cancelled install never removes a pre-existing registration
Cancelling an install uninstalled whatever registration lived in the folder, so cancelling a reinstall of a game the user had installed from the Battle.net client deleted that client's registration. An install now decides ownership once, before it starts: the registrations that were already in the folder belong to someone else and are never touched, including the unfinished registration an earlier cancelled install left behind. The decision is snapshotted into SavedQueue when the queue accepts the task, so a resumed or restored install keeps it instead of re-reading a folder that may already hold this task's own registration. The cancellation also holds the folder against a concurrent uninstall, only removes the uids it saw, and only deletes a folder it created itself. The queue publishes the cleanup key so a second cancellation of the same game cannot start a parallel cleanup.
This commit is contained in:
1 parent
e309280b65
commit
b0904cc65b
7 files changed
+830
-77
No files matched your search
@@ -223,18 +223,12 @@ object BattleNet {
|
||||
*/
|
||||
fun launchCode(context: Context, uid: String, folder: File?): String? {
|
||||
if (folder == null) return runCatching { games(context) }.getOrNull()?.let { launchCode(it, uid, null) }
|
||||
val at = runCatching { registrationsIn(context, folder) }.getOrNull()
|
||||
at?.firstOrNull { (registered, _) -> sameTitle(registered, uid) }?.let { return it.second.code }
|
||||
// games() keeps one copy per launch code; the registrations of this folder are authoritative.
|
||||
runCatching { registrationsAt(context, uid, folder) }.getOrNull()?.firstOrNull()
|
||||
?.let { registered -> title(registered)?.code?.let { return it } }
|
||||
return runCatching { games(context) }.getOrNull()?.let { launchCode(it, uid, folder) }
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -246,39 +240,53 @@ object BattleNet {
|
||||
return a.uid == b.uid || (a.code == b.code && a.product != null && a.product == b.product)
|
||||
}
|
||||
|
||||
/**
|
||||
* The registrations that resolve to [folder], whatever uid they were written under.
|
||||
*
|
||||
* [games] deduplicates by launch code, so a second copy of one game in another folder is not in
|
||||
* its list; a per-folder lookup therefore reads the registration sources directly. `null` means
|
||||
* a source could not be read.
|
||||
*/
|
||||
internal fun registrationsIn(context: Context, folder: File): List<Pair<String, Title>>? {
|
||||
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 { productDbInstalls(agentFile.readBytes()) }.getOrNull() ?: return null
|
||||
val registry = if (!registryFile.exists()) emptyList()
|
||||
else runCatching { registryFile.useLines { uninstallEntries(it).toList() } }.getOrNull() ?: return null
|
||||
val products = agent.filter { it.product.isNotEmpty() }.associate { it.uid.lowercase() to it.product }
|
||||
return (registry + agent.map { it.uid to it.path }).mapNotNull { (uid, path) ->
|
||||
if (hostFolder(context, path)?.absolutePath != folder.absolutePath) return@mapNotNull null
|
||||
val found = title(uid) ?: products[uid.lowercase()]?.let(::titleForProduct) ?: return@mapNotNull null
|
||||
uid to found
|
||||
}.distinctBy { it.first.lowercase() }
|
||||
}
|
||||
|
||||
/** 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.isFile && runCatching { agent.readBytes() }.isFailure) return false
|
||||
if (registry.isFile && runCatching { registry.useLines { uninstallEntries(it).toList() } }.isFailure) 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 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>()
|
||||
@@ -394,6 +402,25 @@ 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) ->
|
||||
|
||||
@@ -12,11 +12,13 @@ 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
|
||||
@@ -32,7 +34,6 @@ object BattleNetInstall {
|
||||
internal const val STATE = "BNET_STATE "
|
||||
internal const val DONE = "BNET_DONE "
|
||||
internal const val ERROR = "BNET_ERROR "
|
||||
internal const val UID = "BNET_UID "
|
||||
private const val CN = "cn"
|
||||
private const val BUILD_INFO = ".build.info"
|
||||
private const val CHECK_AGAIN_MS = 30 * 60_000L
|
||||
@@ -111,11 +112,18 @@ 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, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl,
|
||||
Store.BATTLENET, tagged.id, tagged.title, cover = tagged.tallImageUrl ?: tagged.imageUrl,
|
||||
location = StoreInstallRoot.labelFor(app, folder),
|
||||
cleanupKey = "${Store.BATTLENET.id}:${tagged.id}",
|
||||
)
|
||||
DownloadQueue.enqueue(app, entry) { BattleNetInstaller(app, item, folder, update) }
|
||||
val ownership = Ownership(tagged)
|
||||
DownloadQueue.enqueue(app, entry, onAccepted = {
|
||||
SavedQueue.remember(app, tagged, folder.parentFile?.parentFile)
|
||||
}) { BattleNetInstaller(app, tagged, folder, update, ownership) }
|
||||
}
|
||||
|
||||
fun update(context: Context, game: InstalledStoreGame) {
|
||||
@@ -127,9 +135,7 @@ object BattleNetInstall {
|
||||
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 {
|
||||
val item = updateItem(game, uid)
|
||||
game.folder.parentFile?.parentFile?.let { com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, it) }
|
||||
enqueue(app, item, game.folder, update = true)
|
||||
enqueue(app, updateItem(game, uid), game.folder, update = true)
|
||||
}
|
||||
}, "battlenet-update").start()
|
||||
}
|
||||
@@ -142,15 +148,13 @@ 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"
|
||||
|
||||
internal fun installUid(context: Context, game: InstalledStoreGame): String? {
|
||||
val games = runCatching { BattleNet.games(context) }.getOrNull() ?: return null
|
||||
val folder = game.folder.absolutePath
|
||||
val sameTitle = games.filter { BattleNet.sameTitle(it.uid, game.sidecar.id) }
|
||||
return sameTitle.firstOrNull { it.folder.absolutePath == folder }?.installUid
|
||||
}
|
||||
/** 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.registrationsAt(context, game.sidecar.id, game.folder) }.getOrNull()?.firstOrNull()
|
||||
|
||||
fun uninstall(context: Context, game: InstalledStoreGame): Boolean {
|
||||
if (product(game.sidecar.id) == null || !BattleNet.installed(context)) return false
|
||||
@@ -287,20 +291,44 @@ 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 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)
|
||||
@Volatile private var effectiveUid: String? = null
|
||||
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)
|
||||
@@ -316,7 +344,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()
|
||||
if (!update && folder.mkdirs()) ownership.createdFolder.set(true)
|
||||
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)
|
||||
@@ -330,11 +358,7 @@ internal class BattleNetInstaller(
|
||||
line == BattleNetInstall.STATE + "waiting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_waiting))
|
||||
line == BattleNetInstall.STATE + "queued" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_queued))
|
||||
line == BattleNetInstall.STATE + "starting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_starting))
|
||||
line.startsWith(BattleNetInstall.UID) -> effectiveUid = line.removePrefix(BattleNetInstall.UID).trim().takeIf { it.isNotEmpty() }
|
||||
line.startsWith(BattleNetInstall.DONE) -> {
|
||||
done = runCatching { JSONObject(line.removePrefix(BattleNetInstall.DONE)) }.getOrNull()
|
||||
done?.optString("uid")?.takeIf { it.isNotEmpty() }?.let { effectiveUid = it }
|
||||
}
|
||||
line.startsWith(BattleNetInstall.DONE) -> done = runCatching { JSONObject(line.removePrefix(BattleNetInstall.DONE)) }.getOrNull()
|
||||
line.startsWith(BattleNetInstall.ERROR) -> reason = line.removePrefix(BattleNetInstall.ERROR)
|
||||
}
|
||||
}
|
||||
@@ -364,18 +388,59 @@ internal class BattleNetInstaller(
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (!deleteFiles || update) return
|
||||
Thread({
|
||||
if (started.get() && !ended.await(END_WAIT_S, TimeUnit.SECONDS)) Log.w("BattleNetInstall", "the cancelled install of ${item.id} is still stopping")
|
||||
// The driver may report its uid while this thread waits for the job to stop.
|
||||
val recorded = item.extra[BattleNetInstall.INSTALL_UID] ?: effectiveUid
|
||||
if (recorded == null) Log.w("BattleNetInstall", "cancelled install of ${item.id}: the driver did not report a uid; the registration is left for Battle.net")
|
||||
// Never guess the store id here: the Agent may have installed under a China uid of its own.
|
||||
val gone = recorded != null && BattleNetInstall.agentUninstall(app, recorded)
|
||||
if (folder.isDirectory && (gone || folder.list().isNullOrEmpty())) com.droiddeck.launcher.core.FileUtils.delete(folder)
|
||||
Log.i("BattleNetInstall", "cancelled install of ${item.id}: ${if (gone) "removed" else "left for Battle.net to remove"}")
|
||||
}, "battlenet-cancel").start()
|
||||
if (!deleteFiles || update) {
|
||||
if (update) DownloadQueue.cleanupFinished(queueKey)
|
||||
return
|
||||
}
|
||||
if (!cleanupStarted.compareAndSet(false, true)) return
|
||||
if (!started.get() && !ownership.known) ownership.preexisting = true
|
||||
val path = folder.absolutePath
|
||||
cleanupRunning.add(path)
|
||||
val cleanup = Thread({
|
||||
var discarding = false
|
||||
try {
|
||||
val stopped = !started.get() || ended.await(END_WAIT_S, TimeUnit.SECONDS)
|
||||
if (ownership.preexisting) {
|
||||
Log.i("BattleNetInstall", "cancelled install of ${item.id}: ${path} keeps the registration that existed before the task")
|
||||
} else if (!stopped) {
|
||||
Log.w("BattleNetInstall", "the cancelled install of ${item.id} is still stopping; ${path} is left for Battle.net")
|
||||
} else {
|
||||
StoreInstalls.beginDiscard(folder)
|
||||
discarding = true
|
||||
val found = runCatching { registration() }.getOrNull()
|
||||
if (found == null) {
|
||||
Log.w("BattleNetInstall", "cancelled install of ${item.id}: the registration could not be read; ${path} is left for Battle.net")
|
||||
} else if (found.isEmpty()) {
|
||||
if (ownership.createdFolder.get() && !deleteFolder()) {
|
||||
Log.w("BattleNetInstall", "cancelled install of ${item.id}: ${path} could not be deleted")
|
||||
}
|
||||
} else {
|
||||
for (uid in found.distinct()) uninstall(uid)
|
||||
if (ownership.createdFolder.get() && !deleteFolder()) {
|
||||
Log.w("BattleNetInstall", "cancelled install of ${item.id}: ${path} could not be deleted")
|
||||
}
|
||||
}
|
||||
}
|
||||
} 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 deleteFolder(): Boolean {
|
||||
com.droiddeck.launcher.core.FileUtils.delete(folder)
|
||||
return !folder.exists()
|
||||
}
|
||||
}
|
||||
|
||||
private val cleanupRunning = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
|
||||
private const val END_WAIT_S = 120L
|
||||
@@ -34,6 +34,7 @@ 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,6 +107,7 @@ 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>()
|
||||
@@ -114,7 +115,9 @@ 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) return@synchronized false
|
||||
if (item?.entry?.isActive == true || item?.job != null || key in cleaningUp || key in removing || key in cancelling) {
|
||||
return@synchronized false
|
||||
}
|
||||
removing.add(key)
|
||||
true
|
||||
}
|
||||
@@ -127,7 +130,7 @@ object DownloadQueue {
|
||||
return synchronized(lock) {
|
||||
while (true) {
|
||||
val busy = busyLocked(key)
|
||||
if (!busy && key !in cleaningUp && key !in removing) break
|
||||
if (!busy && key !in cleaningUp && key !in removing && key !in cancelling) break
|
||||
val left = deadline - android.os.SystemClock.uptimeMillis()
|
||||
if (busy && left <= 0) return@synchronized false
|
||||
(lock as Object).wait(if (busy) left else 0L)
|
||||
@@ -192,14 +195,31 @@ 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, factory: () -> DownloadJob) {
|
||||
fun enqueue(context: Context, entry: DownloadEntry, onAccepted: (() -> Unit)? = null, factory: () -> DownloadJob): Boolean {
|
||||
val app = context.applicationContext
|
||||
synchronized(lock) {
|
||||
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 } }
|
||||
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 } }
|
||||
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()
|
||||
@@ -207,6 +227,7 @@ 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) {
|
||||
@@ -274,26 +295,39 @@ 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 { runCatching { item.job?.cancel(deleteFiles = true) } }
|
||||
val deleting = StoreInstalls.collectingDiscards {
|
||||
if (runCatching { item.job?.cancel(deleteFiles = true) }.isFailure) cleanupFinished(cleanupKey)
|
||||
}
|
||||
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 (cleanup) {
|
||||
cleanUpLater(app, key, "store-dl-cancel") { runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }
|
||||
if (!wasRunning && cleanup) {
|
||||
cleanUpLater(app, key, "store-dl-cancel") {
|
||||
if (runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) }.isFailure) cleanupFinished(cleanupKey)
|
||||
}
|
||||
}
|
||||
if (awaitDeletion.isNotEmpty()) cleanUpLater(app, key, "store-dl-cancel-wait") { awaitDeletion.forEach { it.join() } }
|
||||
StoresState.logLine("cancelled \"${item.entry.name}\"")
|
||||
@@ -303,17 +337,27 @@ object DownloadQueue {
|
||||
}
|
||||
|
||||
fun clear(context: Context, key: String) {
|
||||
val app = context.applicationContext
|
||||
val item: Item
|
||||
val cleanup: Boolean
|
||||
var cleanupKey: String? = null
|
||||
var cleanup = false
|
||||
synchronized(lock) {
|
||||
item = items[key] ?: return
|
||||
if (item.entry.state == DownloadState.RUNNING || item.entry.state == DownloadState.QUEUED) return
|
||||
cleanup = (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) && beginCleanup(key)
|
||||
if (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) {
|
||||
cleanup = beginCleanup(key)
|
||||
if (cleanup) {
|
||||
val candidate = item.entry.cleanupKey?.takeIf { item.factory != null }
|
||||
if (candidate != null && cancelling.add(candidate)) cleanupKey = candidate
|
||||
}
|
||||
}
|
||||
items.remove(key)
|
||||
publishLocked()
|
||||
}
|
||||
if (cleanup) cleanUpLater(context.applicationContext, key, "store-dl-clear") { runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }
|
||||
StoreDownloadService.finish(context.applicationContext, key)
|
||||
if (cleanup) cleanUpLater(app, key, "store-dl-clear") {
|
||||
if (runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) }.isFailure) cleanupFinished(cleanupKey)
|
||||
}
|
||||
StoreDownloadService.finish(app, key)
|
||||
}
|
||||
|
||||
fun dismissFinished() {
|
||||
@@ -393,11 +437,27 @@ object DownloadQueue {
|
||||
var error: String? = null
|
||||
try {
|
||||
val job = checkNotNull(item.factory).invoke()
|
||||
synchronized(lock) { item.job = job }
|
||||
var cancelled = false
|
||||
var paused = false
|
||||
synchronized(lock) {
|
||||
item.job = job
|
||||
cancelled = item.cancelled.get()
|
||||
paused = item.pauseRequested
|
||||
}
|
||||
StoresState.logLine("${item.entry.store.label}: fetching manifest for \"${item.entry.name}\"")
|
||||
val deleting = ArrayList<Thread>()
|
||||
try {
|
||||
StoreInstalls.collectingDiscards(deleting) { result = job.run(handle) }
|
||||
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)
|
||||
}
|
||||
} finally {
|
||||
if (deleting.isNotEmpty()) {
|
||||
holdCleanup(item.entry.key)
|
||||
@@ -408,6 +468,9 @@ 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,6 +29,16 @@ 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) {
|
||||
|
||||
@@ -3,11 +3,16 @@ 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.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
|
||||
@@ -26,6 +31,10 @@ 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 = """
|
||||
@@ -394,6 +403,21 @@ class BattleNetTest {
|
||||
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()
|
||||
@@ -405,6 +429,7 @@ class BattleNetTest {
|
||||
))
|
||||
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")))
|
||||
@@ -445,6 +470,216 @@ class BattleNetTest {
|
||||
assertEquals("Fen", BattleNet.launchCode(context, "fen", 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, 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, 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 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, 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 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, 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, 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()
|
||||
@@ -456,6 +691,8 @@ class BattleNetTest {
|
||||
))
|
||||
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"))))
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
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
|
||||
@@ -12,9 +15,11 @@ 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)
|
||||
@@ -117,6 +122,351 @@ 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)
|
||||
|
||||
Reference in new issue
Block a user