mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
feat: add GOG maintenance
This commit is contained in:
1 parent
52fa41767c
commit
198f667bf0
54 files changed
+11840
-26
No files matched your search
@@ -74,6 +74,7 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
|
||||
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
|
||||
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
|
||||
"usr/local/bin/droiddeck-gog-maintenance" to "usr/local/bin/droiddeck-gog-maintenance",
|
||||
"usr/local/bin/droiddeck-battlenet" to "usr/local/bin/droiddeck-battlenet",
|
||||
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
|
||||
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
|
||||
|
||||
@@ -254,6 +254,7 @@ object StoreInstallRoot {
|
||||
val sidecar = StoreGameSidecar.read(folder)
|
||||
when {
|
||||
sidecar == null -> Unfinished(store, null, folder)
|
||||
store == Store.GOG && sidecar.state == StoreGameSidecar.STATE_UPDATING -> null
|
||||
!sidecar.isInstalled -> Unfinished(store, sidecar.id, folder)
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ object StoresState {
|
||||
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
|
||||
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
|
||||
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled }?.let { InstalledStoreGame(it, folder) }
|
||||
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.store == Store.GOG && it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
|
||||
} + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(app) }.getOrDefault(emptyList())
|
||||
val partial = StoreInstallRoot.unfinished(app)
|
||||
val version = if (StoresNative.available) StoresNative.version ?: "" else ""
|
||||
@@ -95,6 +95,7 @@ object StoresState {
|
||||
engine = version
|
||||
accountsLoaded = true
|
||||
}
|
||||
com.droiddeck.launcher.stores.gog.GogMaintenance.checkInstalled(app, onDisk)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,9 @@ data class DownloadEntry(
|
||||
val stageItemsTotal: Int = 0,
|
||||
val diskBytes: Long = 0L,
|
||||
val stagesPassed: Int = 0,
|
||||
val interruptible: Boolean = true,
|
||||
val reusedBytes: Long = 0L,
|
||||
val appliedBytes: Long = 0L,
|
||||
) {
|
||||
fun passed(s: DownloadStage): Boolean = state == DownloadState.INSTALLED || (stagesPassed and (1 shl s.ordinal)) != 0
|
||||
|
||||
|
||||
@@ -21,6 +21,11 @@ object DownloadQueue {
|
||||
fun diskSize(bytes: Long) = update(key) { if (bytes > 0) it.copy(diskBytes = bytes) else it }
|
||||
fun progress(bytesDone: Long, bytesTotal: Long, detail: String? = null, @Suppress("UNUSED_PARAMETER") speedBps: Long = -1L) = measure(key, bytesDone, bytesTotal, detail?.let(::stripSpeed))
|
||||
fun log(line: String) = StoresState.logLine(line)
|
||||
fun interruptible(value: Boolean) = update(key) {
|
||||
check(value || !cancelled.get()) { "The operation was paused before installer application" }
|
||||
it.copy(interruptible = value)
|
||||
}
|
||||
fun maintenance(reusedBytes: Long, appliedBytes: Long) = update(key) { it.copy(reusedBytes = reusedBytes, appliedBytes = appliedBytes) }
|
||||
}
|
||||
|
||||
private fun stripSpeed(s: String): String = s.replace(Regex("\\s+\\S+ [KMG]B/s\\s*$"), "").trimEnd()
|
||||
@@ -166,12 +171,13 @@ object DownloadQueue {
|
||||
fun pause(key: String) {
|
||||
val item = synchronized(lock) { items[key] } ?: return
|
||||
synchronized(lock) {
|
||||
if (!item.entry.interruptible) return
|
||||
if (item.entry.state == DownloadState.QUEUED) { item.entry = item.entry.copy(state = DownloadState.PAUSED, queuePosition = 0); renumber(); publishLocked(); return }
|
||||
if (item.entry.state != DownloadState.RUNNING) return
|
||||
item.pauseRequested = true
|
||||
item.cancelled.set(true)
|
||||
item.job?.cancel(deleteFiles = false)
|
||||
}
|
||||
item.cancelled.set(true)
|
||||
item.job?.cancel(deleteFiles = false)
|
||||
StoresState.logLine("paused \"${item.entry.name}\"")
|
||||
}
|
||||
|
||||
@@ -204,17 +210,19 @@ object DownloadQueue {
|
||||
val wasRunning: Boolean
|
||||
synchronized(lock) {
|
||||
item = items[key] ?: return
|
||||
if (!item.entry.interruptible) return
|
||||
wasRunning = item.entry.state == DownloadState.RUNNING
|
||||
if (wasRunning) {
|
||||
item.cancelled.set(true)
|
||||
item.job?.cancel(deleteFiles = true)
|
||||
}
|
||||
if (!wasRunning) {
|
||||
item.entry = item.entry.copy(state = DownloadState.CANCELLED, queuePosition = 0, finishedAt = System.currentTimeMillis())
|
||||
renumber()
|
||||
publishLocked()
|
||||
}
|
||||
}
|
||||
if (wasRunning) {
|
||||
item.cancelled.set(true)
|
||||
item.job?.cancel(deleteFiles = true)
|
||||
} else {
|
||||
if (!wasRunning) {
|
||||
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-cancel").start()
|
||||
}
|
||||
StoresState.logLine("cancelled \"${item.entry.name}\"")
|
||||
|
||||
@@ -45,7 +45,7 @@ object SavedQueue {
|
||||
val f = File(context.filesDir, FILE)
|
||||
val tmp = File(context.filesDir, "$FILE.tmp")
|
||||
tmp.writeText(out.toString())
|
||||
tmp.renameTo(f)
|
||||
java.nio.file.Files.move(tmp.toPath(), f.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
}.onFailure { Log.w(TAG, "could not save the queue", it) }
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,12 @@ object SavedQueue {
|
||||
for ((item, root, paused) in back) {
|
||||
if (DownloadQueue.entry(key(item)) != null) continue
|
||||
if (paused) DownloadQueue.holdPaused(key(item))
|
||||
StoresState.install(app, item, root)
|
||||
if (item.store == Store.GOG && item.extra.containsKey(com.droiddeck.launcher.stores.gog.GogMaintenance.OPERATION)) {
|
||||
Thread({
|
||||
runCatching { com.droiddeck.launcher.stores.gog.GogMaintenance.restore(app, item) }
|
||||
.onFailure { DownloadQueue.recordFailed(app, DownloadEntry(item.store, item.id, item.title), it.message ?: "GOG recovery failed") }
|
||||
}, "gog-restore").start()
|
||||
} else StoresState.install(app, item, root)
|
||||
}
|
||||
}
|
||||
}, "store-queue-restore").start()
|
||||
|
||||
@@ -33,6 +33,7 @@ object GogAuth {
|
||||
|
||||
@Synchronized
|
||||
private fun saveAccount(context: Context, accessToken: String, refreshToken: String?, userId: String?) {
|
||||
GogMaintenance.reset()
|
||||
var username = ""
|
||||
runCatching {
|
||||
val body = StoreNet.get("https://embed.gog.com/userData.json", bearer = accessToken, userAgent = GALAXY_UA)
|
||||
|
||||
@@ -28,6 +28,7 @@ object GogBackend : StoreBackend {
|
||||
}
|
||||
|
||||
override fun signOut(context: Context) {
|
||||
GogMaintenance.reset()
|
||||
GogPrefs.get(context).edit().remove("library_cache").remove("library_cache_v2").remove("library_synced_at").apply()
|
||||
}
|
||||
|
||||
@@ -53,7 +54,11 @@ object GogBackend : StoreBackend {
|
||||
StoresState.post {
|
||||
StoresState.status.remove(store)
|
||||
when (result) {
|
||||
is GogLibrary.SyncResult.Ok -> { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store) }
|
||||
is GogLibrary.SyncResult.Ok -> {
|
||||
StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) })
|
||||
StoresState.problems.remove(store)
|
||||
GogMaintenance.checkInstalled(app, StoresState.installed)
|
||||
}
|
||||
is GogLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
|
||||
GogLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
|
||||
GogLibrary.SyncResult.Busy -> {}
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.zip.GZIPInputStream
|
||||
import java.util.zip.InflaterInputStream
|
||||
|
||||
internal object GogContent {
|
||||
const val SYSTEM = "https://content-system.gog.com"
|
||||
const val CDN = "https://gog-cdn-fastly.gog.com/content-system"
|
||||
|
||||
fun token(context: Context) = GogAuth.validToken(context) ?: error("Sign in to GOG and retry")
|
||||
|
||||
fun builds(id: String, token: String): JSONObject {
|
||||
val result = json("$SYSTEM/products/$id/os/windows/builds?generation=2", token)
|
||||
if (result.optJSONArray("items")?.length() != 0) return result
|
||||
return json("$SYSTEM/products/$id/os/windows/builds?generation=1", token)
|
||||
}
|
||||
|
||||
fun product(id: String, token: String): JSONObject = json("https://api.gog.com/products/$id?expand=downloads", token)
|
||||
|
||||
fun downloadFilename(url: String): String = java.net.URLDecoder.decode(URL(url).path.substringAfterLast('/').replace("+", "%2B"), "UTF-8")
|
||||
|
||||
fun resolveDownload(download: GogOfflineDownload, token: String): GogOfflineDownload = download.copy(parts = download.parts.map { part ->
|
||||
val resolved = GogDownloadManager.resolveRedirect(part.url, token) ?: error("The GOG download link is unavailable")
|
||||
val connection = URL(resolved).openConnection() as HttpURLConnection
|
||||
try {
|
||||
connection.requestMethod = "HEAD"
|
||||
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
|
||||
check(connection.responseCode in 200..299) { "GOG download metadata failed (HTTP ${connection.responseCode})" }
|
||||
val disposition = connection.getHeaderField("Content-Disposition").orEmpty()
|
||||
val supplied = Regex("filename=\"?([^\";]+)", RegexOption.IGNORE_CASE).find(disposition)?.groupValues?.get(1).orEmpty()
|
||||
val remote = downloadFilename(resolved).takeIf { it.endsWith(".exe", true) || it.endsWith(".bin", true) }.orEmpty()
|
||||
val name = part.name.ifBlank { supplied.ifBlank { remote } }
|
||||
check(name.isNotBlank()) { "GOG did not provide the installer part filename" }
|
||||
part.copy(name = name, size = connection.contentLengthLong.coerceAtLeast(0))
|
||||
} finally { connection.disconnect() }
|
||||
})
|
||||
|
||||
fun json(url: String, token: String? = null): JSONObject {
|
||||
require(URL(url).protocol == "https") { "GOG metadata requires HTTPS" }
|
||||
val connection = URL(url).openConnection() as HttpURLConnection
|
||||
try {
|
||||
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
|
||||
connection.setRequestProperty("User-Agent", GogAuth.GALAXY_UA)
|
||||
if (token != null && URL(url).host.let { it == "gog.com" || it.endsWith(".gog.com") }) connection.setRequestProperty("Authorization", "Bearer $token")
|
||||
check(connection.responseCode in 200..299) { "GOG metadata request failed (HTTP ${connection.responseCode})" }
|
||||
val raw = connection.inputStream.readBytes()
|
||||
val text = when {
|
||||
raw.size > 1 && raw[0] == 0x78.toByte() -> InflaterInputStream(raw.inputStream()).bufferedReader().use { it.readText() }
|
||||
raw.size > 1 && raw[0] == 0x1f.toByte() && raw[1] == 0x8b.toByte() -> GZIPInputStream(raw.inputStream()).bufferedReader().use { it.readText() }
|
||||
else -> raw.toString(Charsets.UTF_8)
|
||||
}
|
||||
return JSONObject(text)
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
|
||||
fun snapshot(old: GogInstallRecord, build: GogBuild, token: String,
|
||||
metadata: (String, String?) -> JSONObject = ::json): GogInstallRecord {
|
||||
check(build.link.isNotBlank()) { "GOG build manifest is unavailable" }
|
||||
val manifest = metadata(build.link, token)
|
||||
val files = JSONArray()
|
||||
val depots = if (build.generation == 1) manifest.optJSONObject("product")?.optJSONArray("depots") ?: manifest.optJSONArray("depot") else manifest.optJSONArray("depots")
|
||||
check(depots != null) { "GOG build has no depot list" }
|
||||
val resolvedLanguage = StoreLanguage.pick(StoreLanguage.codesFromDepots(depots), old.language)
|
||||
val selectedBitness = if (depots.objects().any { it.optJSONArray("osBitness")?.strings()?.contains("64") == true }) "64" else "32"
|
||||
val owned = if (old.products.any { it != old.id }) StoreNet.get("https://embed.gog.com/user/data/games", bearer = token)?.let { JSONObject(it).optJSONArray("owned")?.strings()?.toSet() } else emptySet()
|
||||
val products = old.products.filter { it == old.id || owned?.contains(it) == true }
|
||||
check(old.products.all { it == old.id || owned?.contains(it) == true }) { "Could not confirm ownership of installed GOG DLC" }
|
||||
for (depot in depots.objects()) {
|
||||
if (depot.has("redist")) continue
|
||||
val ids = depot.optJSONArray("gameIDs")?.strings() ?: listOf(depot.optString("productId", old.id))
|
||||
val product = ids.firstOrNull { it in products } ?: continue
|
||||
val languages = depot.optJSONArray("languages")?.strings().orEmpty()
|
||||
if (!languageSelected(languages, resolvedLanguage)) continue
|
||||
val bitness = depot.optJSONArray("osBitness")?.strings().orEmpty()
|
||||
if (bitness.isNotEmpty() && selectedBitness !in bitness) continue
|
||||
val hash = depot.optString("manifest")
|
||||
val content = when {
|
||||
hash.isNotEmpty() && build.generation == 2 -> metadata("$CDN/v2/meta/${cdnPath(hash)}", null)
|
||||
hash.isNotEmpty() -> {
|
||||
val timestamp = manifest.getJSONObject("product").getString("timestamp")
|
||||
metadata("$CDN/v1/manifests/$product/windows/$timestamp/$hash", token)
|
||||
}
|
||||
depot.has("files") -> JSONObject().put("depot", depot)
|
||||
else -> error("GOG depot manifest is missing")
|
||||
}
|
||||
val entries = content.getJSONObject("depot").optJSONArray(if (build.generation == 2) "items" else "files") ?: error("GOG depot files are missing")
|
||||
for (entry in entries.objects()) {
|
||||
val type = entry.optString("type")
|
||||
check(type != "DepotLink") { "This GOG build contains unsupported file links" }
|
||||
val support = depot.optBoolean("support") || entry.optBoolean("support") || entry.optJSONArray("flags")?.strings()?.contains("support") == true
|
||||
val relative = entry.getString("path").replace('\\', '/').trimEnd('/').let { if (build.generation == 1) it.trimStart('/') else it }
|
||||
val path = if (support) (if (build.generation == 1) "support/$relative" else "support/$product/$relative") else relative
|
||||
val directory = type == "DepotDirectory" || entry.has("directory")
|
||||
val chunks = entry.optJSONArray("chunks") ?: JSONArray()
|
||||
val size = if (build.generation == 2) chunks.objects().sumOf { it.optLong("size") } else entry.optLong("size")
|
||||
files.put(JSONObject().put("path", path).put("size", size).put("directory", directory)
|
||||
.put("md5", entry.optString("md5").ifBlank { entry.optString("hash") }.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) }.orEmpty())
|
||||
.put("sha256", entry.optString("sha256")).put("chunks", chunks).put("product", product)
|
||||
.put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?')))
|
||||
}
|
||||
}
|
||||
check(files.length() > 0) { "GOG build contains no matching files" }
|
||||
return old.copy(source = "depot", generation = build.generation, build = build.id, version = build.version,
|
||||
branch = build.branch, language = resolvedLanguage, manifest = sanitize(manifest), files = files, products = products, verified = true)
|
||||
}
|
||||
|
||||
fun languageSelected(list: List<String>, selected: String): Boolean = list.any { it.equals("Neutral", true) } || StoreLanguage.depotMatchesResolved(list.toTypedArray(), selected)
|
||||
|
||||
fun cdnPath(hash: String): String {
|
||||
require(hash.matches(Regex("[a-fA-F0-9]{32,64}"))) { "Invalid GOG content hash" }
|
||||
return "${hash.take(2)}/${hash.substring(2, 4)}/$hash"
|
||||
}
|
||||
|
||||
fun links(record: GogInstallRecord, token: String, patches: Boolean = false): JSONObject {
|
||||
val out = JSONObject()
|
||||
for (id in record.products) {
|
||||
val path = if (record.generation == 1) "/windows/${record.manifest.optJSONObject("product")?.optString("timestamp")}/" else "/"
|
||||
val query = "_version=2&" + (if (record.generation == 1) "type=depot" else "generation=2") + "&path=${java.net.URLEncoder.encode(path, "UTF-8")}" + if (patches) "&root=%2Fpatches%2Fstore" else ""
|
||||
val response = json("$SYSTEM/products/$id/secure_link?$query", token)
|
||||
val bases = response.optJSONArray("urls")?.objects().orEmpty().mapNotNull { item ->
|
||||
val params = item.optJSONObject("parameters")
|
||||
var url = item.optString("url_format")
|
||||
params?.keys()?.forEach { key -> url = url.replace("{$key}", params.getString(key)) }
|
||||
url.takeIf { it.startsWith("https://") }
|
||||
}
|
||||
check(bases.isNotEmpty()) { "GOG refused a download link" }
|
||||
out.put(id, JSONArray(bases))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun patches(old: GogInstallRecord, target: GogInstallRecord, token: String): JSONArray {
|
||||
if (old.generation != 2 || target.generation != 2 || old.build.isBlank() || old.build == target.build) return JSONArray()
|
||||
return runCatching {
|
||||
val index = json("$SYSTEM/products/${old.id}/patches?_version=4&from_build_id=${old.build}&to_build_id=${target.build}", token)
|
||||
val meta = json(index.getString("link"), token)
|
||||
if (meta.optString("algorithm") != "xdelta3") return@runCatching JSONArray()
|
||||
val result = JSONArray()
|
||||
for (depot in meta.getJSONArray("depots").objects()) {
|
||||
if (depot.optString("productId") !in target.products || !languageSelected(depot.optJSONArray("languages")?.strings().orEmpty(), target.language)) continue
|
||||
val data = json("$CDN/v2/patches/meta/${cdnPath(depot.getString("manifest"))}")
|
||||
for (item in data.getJSONObject("depot").getJSONArray("items").objects()) if (item.optString("type") == "DepotDiff")
|
||||
result.put(JSONObject(item.toString()).put("product", depot.getString("productId")))
|
||||
}
|
||||
result
|
||||
}.getOrElse { JSONArray() }
|
||||
}
|
||||
|
||||
fun setupFiles(record: GogInstallRecord, token: String): Pair<JSONArray, JSONObject>? {
|
||||
if (!record.manifest.optBoolean("scriptInterpreter")) return null
|
||||
if (record.files.objects().none { file -> record.products.any { file.optString("path").substringAfterLast('/') == "goggame-$it.script" } }) return null
|
||||
val index = json("$SYSTEM/dependencies/repository?generation=2")
|
||||
val repository = json(index.getString("repository_manifest"))
|
||||
val depot = repository.getJSONArray("depots").objects().firstOrNull { it.optString("dependencyId") == "ISI" }
|
||||
?: error("GOG setup interpreter is unavailable")
|
||||
val content = json("$CDN/v2/dependencies/meta/${cdnPath(depot.getString("manifest"))}")
|
||||
val files = JSONArray()
|
||||
for (entry in content.getJSONObject("depot").getJSONArray("items").objects()) {
|
||||
if (entry.optString("type") != "DepotFile") continue
|
||||
val chunks = entry.getJSONArray("chunks")
|
||||
files.put(JSONObject().put("path", "support/" + entry.getString("path").replace('\\', '/'))
|
||||
.put("size", chunks.objects().sumOf { it.getLong("size") }).put("md5", entry.optString("md5"))
|
||||
.put("chunks", chunks).put("product", "redist"))
|
||||
}
|
||||
val response = json("$SYSTEM/open_link?generation=2&_version=2&path=%2Fdependencies%2Fstore%2F", token)
|
||||
val bases = GogDownloadManager.parseCdnUrls(response.toString())
|
||||
check(bases.isNotEmpty()) { "GOG setup download links are unavailable" }
|
||||
return files to JSONObject().put("redist", JSONArray(bases))
|
||||
}
|
||||
|
||||
fun sanitize(value: JSONObject): JSONObject {
|
||||
val result = JSONObject()
|
||||
for (key in value.keys()) {
|
||||
if (key.lowercase() in setOf("clientsecret", "access_token", "refresh_token", "link", "urls", "url")) continue
|
||||
val v = value.get(key)
|
||||
result.put(key, when (v) { is JSONObject -> sanitize(v); is JSONArray -> JSONArray((0 until v.length()).map { i -> v.get(i).let { if (it is JSONObject) sanitize(it) else it } }); else -> v })
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -106,7 +106,7 @@ public final class GogDownloadManager {
|
||||
String builds1Json = httpGet(builds1Url, null);
|
||||
if (builds1Json == null) builds1Json = httpGet(builds1Url, token);
|
||||
if (builds1Json == null) throw new InstallException("No builds available for this game");
|
||||
Gen1Outcome one = runGen1(ctx, game, token, builds1Json, installPath, cb, cancelled);
|
||||
Gen1Outcome one = runGen1(ctx, game, token, builds1Json, installPath, cb, cancelled, lang);
|
||||
if (one.result != null || cancelled.get()) return one.result;
|
||||
if (!"NO_CS_BUILDS".equals(one.error)) throw new InstallException("Download failed: " + one.error);
|
||||
cb.onProgress("No Galaxy builds; fetching the installer…", 12);
|
||||
@@ -250,6 +250,11 @@ public final class GogDownloadManager {
|
||||
if (anyFailed.get()) { out.error = "one or more chunks failed to download"; return out; }
|
||||
|
||||
cb.onProgress("Finishing…", 96);
|
||||
try {
|
||||
GogMaintenance.captureDepot(game.gameId, installPath, gm.buildId, buildsJson, manifest, new JSONArray(depotJsons), resolved);
|
||||
} catch (Exception e) {
|
||||
cb.onLog("gog: maintenance inventory not recorded: " + e.getMessage());
|
||||
}
|
||||
writeFile(new File(installPath, MARKER), ("{\"gameId\":\"" + game.gameId + "\",\"buildId\":\"" + gm.buildId + "\"}").getBytes("UTF-8"));
|
||||
deleteCounted(new File(installPath, ".gog_chunks"), cb);
|
||||
String clientId = manifest.optString("clientId", null);
|
||||
@@ -279,7 +284,7 @@ public final class GogDownloadManager {
|
||||
String buildId = null, manifestUrl = null;
|
||||
for (int i = 0; i < items.length(); i++) {
|
||||
JSONObject item = items.getJSONObject(i);
|
||||
if ("windows".equals(item.optString("os"))) {
|
||||
if ("windows".equals(item.optString("os")) && (item.isNull("branch") || item.optString("branch").isEmpty())) {
|
||||
buildId = item.optString("build_id");
|
||||
manifestUrl = item.optString("link");
|
||||
if (manifestUrl == null || manifestUrl.isEmpty()) manifestUrl = item.optString("meta_url");
|
||||
@@ -328,7 +333,7 @@ public final class GogDownloadManager {
|
||||
|
||||
private static final class Gen1Outcome { Result result; String error; }
|
||||
|
||||
private static Gen1Outcome runGen1(Context ctx, GogGame game, String token, String buildsJson, File installPath, Callback cb, AtomicBoolean cancelled) {
|
||||
private static Gen1Outcome runGen1(Context ctx, GogGame game, String token, String buildsJson, File installPath, Callback cb, AtomicBoolean cancelled, String language) {
|
||||
Gen1Outcome out = new Gen1Outcome();
|
||||
try {
|
||||
JSONObject builds = new JSONObject(buildsJson);
|
||||
@@ -346,6 +351,15 @@ public final class GogDownloadManager {
|
||||
String manifestStr = decompressBytes(raw);
|
||||
if (manifestStr == null) { out.error = "manifest decompress failed"; return out; }
|
||||
JSONObject manifest = new JSONObject(manifestStr);
|
||||
if (manifest.has("product")) {
|
||||
try {
|
||||
out.result = GogMaintenance.installContent(ctx, game, installPath, builds, language, cb, cancelled);
|
||||
if (out.result == null && !cancelled.get()) out.error = "no usable public Windows build";
|
||||
} catch (Exception e) {
|
||||
out.error = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
JSONArray depots = manifest.optJSONArray("depot");
|
||||
if (depots == null) { out.error = "no depot array"; return out; }
|
||||
List<Gen1File> files = new ArrayList<>();
|
||||
@@ -472,6 +486,7 @@ public final class GogDownloadManager {
|
||||
String exe = pickExe(installPath, null, game.title);
|
||||
if (exe.isEmpty()) throw new InstallException("The installer was extracted but no game executable was found");
|
||||
cb.onLog("gog: installer extracted natively; game exe " + exe);
|
||||
GogMaintenance.captureOffline(game.gameId, installPath, downloads);
|
||||
return new Result(exe, "", total);
|
||||
} catch (InstallerException e) {
|
||||
throw e;
|
||||
@@ -576,13 +591,13 @@ public final class GogDownloadManager {
|
||||
return cleaned.isEmpty() ? "game" : cleaned;
|
||||
}
|
||||
|
||||
private static String resolveRedirect(String url, String token) {
|
||||
static String resolveRedirect(String url, String token) {
|
||||
try {
|
||||
if (url.startsWith("/")) url = "https://www.gog.com" + url;
|
||||
for (int hop = 0; hop < 5; hop++) {
|
||||
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
|
||||
conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setInstanceFollowRedirects(false);
|
||||
if (token != null) conn.setRequestProperty("Authorization", "Bearer " + token);
|
||||
if (token != null && (new URL(url).getHost().equals("gog.com") || new URL(url).getHost().endsWith(".gog.com"))) conn.setRequestProperty("Authorization", "Bearer " + token);
|
||||
int code = conn.getResponseCode();
|
||||
String location = conn.getHeaderField("Location");
|
||||
if (code == 301 || code == 302 || code == 303 || code == 307 || code == 308) {
|
||||
@@ -686,6 +701,7 @@ public final class GogDownloadManager {
|
||||
cb.onBytes(shown, planned, speedBps.get());
|
||||
}
|
||||
@Override public void onLog(String line) { cb.onLog(line); }
|
||||
@Override public void onMaintenance(long networkBytes, long reusedBytes, long appliedBytes) {}
|
||||
@Override public void onComplete(boolean success, boolean wasCancelled, boolean linkExpiry, String error, long bytesWritten, int filesDone) {
|
||||
okRef.set(success); linkExpiryRef.set(linkExpiry); errRef.set(error == null ? "" : error); latch.countDown();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.security.MessageDigest
|
||||
|
||||
internal object GogEstimate {
|
||||
data class Size(val download: Long, val required: Long)
|
||||
private data class Chunk(val file: File, val offset: Long)
|
||||
|
||||
fun range(file: File, offset: Long, size: Long, md5: String): Boolean {
|
||||
if (!file.isFile || offset < 0 || size < 0 || file.length() < offset + size || !md5.matches(Regex("[a-fA-F0-9]{32}"))) return false
|
||||
return runCatching {
|
||||
RandomAccessFile(file, "r").use { input ->
|
||||
input.seek(offset)
|
||||
val digest = MessageDigest.getInstance("MD5"); val buffer = ByteArray(64 * 1024); var left = size
|
||||
while (left > 0) { val n = input.read(buffer, 0, minOf(left, buffer.size.toLong()).toInt()); check(n > 0); digest.update(buffer, 0, n); left -= n }
|
||||
digest.digest().joinToString("") { "%02x".format(it) }.equals(md5, true)
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
fun calculate(folder: File, old: GogInstallRecord, target: GogInstallRecord, patches: JSONArray, reuseChunks: Boolean = true): Size {
|
||||
val reusable = HashMap<Pair<String, Long>, MutableList<Chunk>>()
|
||||
for (file in old.files.objects()) {
|
||||
val source = GogFiles.inside(folder, file.getString("path")); var offset = 0L
|
||||
for (chunk in file.optJSONArray("chunks")?.objects().orEmpty()) {
|
||||
reusable.getOrPut(chunk.optString("md5").lowercase() to chunk.optLong("size")) { ArrayList() }.add(Chunk(source, offset))
|
||||
offset += chunk.optLong("size")
|
||||
}
|
||||
}
|
||||
var download = 0L; var required = 0L
|
||||
for (file in target.files.objects()) {
|
||||
if (file.optBoolean("directory") || GogFiles.matches(folder, file)) continue
|
||||
val chunks = file.optJSONArray("chunks")?.objects().orEmpty()
|
||||
val stamp = MessageDigest.getInstance("MD5").digest(file.getString("path").toByteArray()).joinToString("") { "%02x".format(it) }
|
||||
val stage = File(GogFiles.dir(folder), "stage/$stamp")
|
||||
var offset = 0L
|
||||
var cost = if (chunks.isEmpty()) file.getLong("size") else chunks.sumOf { chunk ->
|
||||
val size = chunk.getLong("size"); val hash = chunk.getString("md5")
|
||||
val exists = reuseChunks && (range(stage, offset, size, hash) || reusable[hash.lowercase() to size].orEmpty().any { range(it.file, it.offset, size, hash) })
|
||||
offset += size
|
||||
if (exists) 0L else chunk.optLong("compressedSize")
|
||||
}
|
||||
val patch = patches.objects().firstOrNull { it.optString("path_target").replace('\\', '/') == file.getString("path") }
|
||||
if (reuseChunks && patch != null) {
|
||||
val source = GogFiles.inside(folder, patch.getString("path_source").replace('\\', '/'))
|
||||
val delta = patch.getJSONArray("chunks").objects().sumOf { it.optLong("compressedSize") }
|
||||
if (delta < cost && source.isFile && GogFiles.hash(source).equals(patch.getString("md5_source"), true)) cost = delta
|
||||
}
|
||||
download = Math.addExact(download, cost)
|
||||
required = Math.addExact(required, maxOf(0, file.getLong("size") - stage.length()) + cost)
|
||||
}
|
||||
return Size(download, required)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.zip.InflaterInputStream
|
||||
|
||||
internal object GogFallback {
|
||||
fun transfer(folder: File, plan: JSONObject, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean,
|
||||
callback: GogDownloadManager.Callback? = null) {
|
||||
val stageRoot = File(GogFiles.dir(folder), "stage").apply { mkdirs() }
|
||||
val files = plan.getJSONArray("files")
|
||||
GogFiles.validate(files, folder)
|
||||
var wire = 0L
|
||||
fun progress(n: Int) { wire += n; handle?.progress(wire, plan.optLong("downloadBytes").coerceAtLeast(wire)); callback?.onBytes(wire, plan.optLong("downloadBytes").coerceAtLeast(wire), 0) }
|
||||
for ((index, item) in files.objects().withIndex()) {
|
||||
if (stop.get()) return
|
||||
val destination = GogFiles.inside(folder, item.getString("path"))
|
||||
if (item.optBoolean("directory")) { java.nio.file.Files.createDirectories(destination.toPath()); continue }
|
||||
if (GogFiles.matches(folder, item)) continue
|
||||
val stage = File(stageRoot, java.security.MessageDigest.getInstance("MD5").digest(item.getString("path").toByteArray()).joinToString("") { "%02x".format(it) })
|
||||
val chunks = item.optJSONArray("chunks")?.objects().orEmpty()
|
||||
FileOutputStream(stage).use { output ->
|
||||
if (chunks.isNotEmpty()) {
|
||||
for (chunk in chunks) {
|
||||
if (stop.get()) return
|
||||
val packed = File(stageRoot, "${stage.name}.packed")
|
||||
val urls = endpoints(plan.getJSONObject("links"), item.getString("product"), GogContent.cdnPath(chunk.getString("compressedMd5")))
|
||||
download(urls, packed, chunk.getLong("compressedSize"), stop, ::progress)
|
||||
check(GogFiles.hash(packed).equals(chunk.getString("compressedMd5"), true)) { "GOG compressed chunk checksum mismatch" }
|
||||
val digest = java.security.MessageDigest.getInstance("MD5")
|
||||
var count = 0L
|
||||
packed.inputStream().buffered().use { raw ->
|
||||
raw.mark(2); val first = raw.read(); raw.reset()
|
||||
val stored = chunk.getLong("size") == chunk.getLong("compressedSize") && chunk.getString("md5").equals(chunk.getString("compressedMd5"), true)
|
||||
val input = if (!stored && first == 0x78) InflaterInputStream(raw) else raw
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
if (stop.get()) return
|
||||
val n = input.read(buffer); if (n < 0) break
|
||||
count += n; check(count <= chunk.getLong("size")) { "GOG chunk exceeds expected size" }
|
||||
digest.update(buffer, 0, n); output.write(buffer, 0, n)
|
||||
}
|
||||
}
|
||||
check(count == chunk.getLong("size") && digest.digest().joinToString("") { "%02x".format(it) }.equals(chunk.getString("md5"), true)) { "GOG chunk checksum mismatch" }
|
||||
packed.delete()
|
||||
}
|
||||
} else if (item.getLong("size") > 0) {
|
||||
val remote = item.getString("remotePath")
|
||||
val urls = if (remote.startsWith("https://")) listOf(remote) else endpoints(plan.getJSONObject("links"), item.getString("product"), remote.trimStart('/'))
|
||||
val range = item.getLong("offset")
|
||||
val raw = File(stageRoot, "${stage.name}.range")
|
||||
download(urls, raw, item.getLong("size"), stop, ::progress, range)
|
||||
raw.inputStream().use { it.copyTo(output) }; raw.delete()
|
||||
}
|
||||
output.fd.sync()
|
||||
}
|
||||
if (stop.get()) return
|
||||
check(stage.length() == item.getLong("size")) { "GOG file size mismatch" }
|
||||
if (item.optString("md5").isNotBlank()) check(GogFiles.hash(stage).equals(item.getString("md5"), true)) { "GOG file checksum mismatch" }
|
||||
if (item.optString("sha256").isNotBlank()) check(GogFiles.hash(stage, "SHA-256").equals(item.getString("sha256"), true)) { "GOG file checksum mismatch" }
|
||||
destination.parentFile!!.mkdirs()
|
||||
GogFiles.inside(folder, item.getString("path"))
|
||||
GogFiles.replace(stage, destination)
|
||||
handle?.stage(DownloadStage.INSTALL); handle?.stageProgress((index + 1).toLong(), files.length().toLong())
|
||||
callback?.onProgress("Downloading: ${destination.name}", ((index + 1) * 100 / files.length()))
|
||||
}
|
||||
val targetPaths = files.objects().mapTo(HashSet()) { it.getString("path").lowercase(java.util.Locale.ROOT) }
|
||||
for (old in plan.optJSONArray("oldFiles")?.objects().orEmpty()) {
|
||||
if (stop.get()) return
|
||||
if (old.getString("path").lowercase(java.util.Locale.ROOT) !in targetPaths && GogFiles.matches(folder, old))
|
||||
check(GogFiles.inside(folder, old.getString("path")).delete()) { "Could not remove obsolete GOG file" }
|
||||
}
|
||||
}
|
||||
|
||||
fun endpoints(links: JSONObject, product: String, path: String): List<String> = links.getJSONArray(product).strings().map { base ->
|
||||
if (base.contains("{GALAXY_PATH}")) base.replace("{GALAXY_PATH}", path)
|
||||
else base.substringBefore('?').trimEnd('/') + "/" + path + if ('?' in base) "?" + base.substringAfter('?') else ""
|
||||
}
|
||||
|
||||
fun download(urls: List<String>, destination: File, size: Long, stop: AtomicBoolean, progress: (Int) -> Unit, range: Long? = null) {
|
||||
var failure: Throwable? = null
|
||||
for (attempt in 0..2) for (url in urls) {
|
||||
if (stop.get()) return
|
||||
val connection = URL(url).openConnection() as HttpURLConnection
|
||||
try {
|
||||
check(URL(url).protocol == "https" || URL(url).host in setOf("127.0.0.1", "localhost"))
|
||||
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
|
||||
if (range != null) connection.setRequestProperty("Range", "bytes=$range-${range + size - 1}")
|
||||
check(connection.responseCode == if (range == null) 200 else 206) { "GOG download failed (HTTP ${connection.responseCode})" }
|
||||
FileOutputStream(destination).use { output ->
|
||||
connection.inputStream.use { input ->
|
||||
val buffer = ByteArray(64 * 1024); var count = 0L
|
||||
while (true) {
|
||||
if (stop.get()) return
|
||||
val n = input.read(buffer); if (n < 0) break
|
||||
count += n; check(size <= 0 || count <= size) { "GOG response exceeds expected size" }
|
||||
output.write(buffer, 0, n); progress(n)
|
||||
}
|
||||
check(size <= 0 || count == size) { "Incomplete GOG download" }
|
||||
}
|
||||
output.fd.sync()
|
||||
}
|
||||
return
|
||||
} catch (e: Exception) { failure = e }
|
||||
finally { connection.disconnect() }
|
||||
}
|
||||
throw failure ?: IllegalStateException("No GOG download URL")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.nio.file.StandardCopyOption
|
||||
import java.security.MessageDigest
|
||||
import java.util.Locale
|
||||
|
||||
internal enum class GogOperation { UPDATE, REPAIR, PATCH, REFRESH }
|
||||
|
||||
internal data class GogInstallRecord(
|
||||
val id: String,
|
||||
val source: String,
|
||||
val generation: Int = 0,
|
||||
val build: String = "",
|
||||
val version: String = "",
|
||||
val branch: String = "",
|
||||
val language: String = "en-US",
|
||||
val products: List<String> = listOf(id),
|
||||
val manifest: JSONObject = JSONObject(),
|
||||
val files: JSONArray = JSONArray(),
|
||||
val verified: Boolean = true,
|
||||
) {
|
||||
fun json() = JSONObject().put("schema", 1).put("id", id).put("source", source)
|
||||
.put("generation", generation).put("build", build).put("version", version).put("branch", branch)
|
||||
.put("language", language).put("products", JSONArray(products)).put("manifest", manifest)
|
||||
.put("files", files).put("verified", verified)
|
||||
|
||||
fun write(folder: File) = GogFiles.write(File(GogFiles.dir(folder), "installed.json"), json())
|
||||
|
||||
companion object {
|
||||
fun parse(o: JSONObject): GogInstallRecord {
|
||||
require(o.optInt("schema") == 1) { "Unsupported GOG installation record" }
|
||||
return GogInstallRecord(o.getString("id"), o.getString("source"), o.optInt("generation"),
|
||||
o.optString("build"), o.optString("version"), o.optString("branch"), o.optString("language", "en-US"),
|
||||
o.optJSONArray("products")?.strings().orEmpty().ifEmpty { listOf(o.getString("id")) },
|
||||
o.optJSONObject("manifest") ?: JSONObject(), o.optJSONArray("files") ?: JSONArray(), o.optBoolean("verified", true))
|
||||
}
|
||||
|
||||
fun read(folder: File): GogInstallRecord? = GogFiles.read(File(GogFiles.dir(folder), "installed.json"))?.let(::parse)
|
||||
|
||||
fun authenticBuild(folder: File, id: String): String = GogFiles.read(File(folder, "goggame-$id.id"))?.optString("buildId").orEmpty()
|
||||
.ifBlank { GogFiles.read(File(folder, "goggame-$id.info"))?.optString("buildId").orEmpty() }
|
||||
|
||||
fun migrate(folder: File, sidecar: StoreGameSidecar): GogInstallRecord {
|
||||
read(folder)?.let { require(it.id == sidecar.id); return it }
|
||||
val legacy = GogFiles.read(File(folder, "_gog_manifest.json"))
|
||||
val info = GogFiles.read(File(folder, "goggame-${sidecar.id}.info"))
|
||||
val build = authenticBuild(folder, sidecar.id).ifBlank { legacy?.optString("buildId").orEmpty().ifBlank { sidecar.installVersion } }
|
||||
val ids = folder.listFiles().orEmpty().mapNotNull { Regex("goggame-([0-9]+)\\.info").matchEntire(it.name)?.groupValues?.get(1) }
|
||||
return GogInstallRecord(sidecar.id, if (legacy != null || sidecar.installVersion.isNotBlank()) "depot" else "offline",
|
||||
legacy?.optInt("generation", if (build.isNotBlank()) 2 else 0) ?: if (build.isNotBlank()) 2 else 0,
|
||||
build, info?.optString("versionName").orEmpty(), language = sidecar.extra[com.droiddeck.launcher.stores.StoreLanguage.EXTRA] ?: "en-US",
|
||||
products = (listOf(sidecar.id) + ids).distinct()).also { it.write(folder) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal object GogFiles {
|
||||
fun dir(folder: File): File = inside(folder, ".droiddeck-gog").apply { mkdirs() }
|
||||
fun journal(folder: File): File = File(dir(folder), "operation.json")
|
||||
|
||||
fun inside(root: File, raw: String): File {
|
||||
val path = raw.replace('\\', '/')
|
||||
require(path.isNotBlank() && !path.startsWith('/') && ':' !in path && '\u0000' !in path &&
|
||||
path.split('/').none { it.isEmpty() || it == "." || it == ".." }) { "Invalid GOG path: $raw" }
|
||||
val base = root.canonicalFile
|
||||
var out = base
|
||||
for (part in path.split('/')) {
|
||||
out = File(out, part)
|
||||
require(!Files.isSymbolicLink(out.toPath())) { "GOG path is a symbolic link: $raw" }
|
||||
}
|
||||
require(out.canonicalFile.toPath().startsWith(base.toPath())) { "GOG path leaves installation" }
|
||||
return out
|
||||
}
|
||||
|
||||
fun read(file: File): JSONObject? {
|
||||
require(!Files.isSymbolicLink(file.toPath())) { "GOG metadata is a symbolic link" }
|
||||
return if (!file.exists()) null else JSONObject(file.readText())
|
||||
}
|
||||
|
||||
fun write(file: File, value: JSONObject) {
|
||||
require(!Files.isSymbolicLink(file.toPath()))
|
||||
file.parentFile!!.mkdirs()
|
||||
val tmp = File.createTempFile(".gog-", ".stage", file.parentFile)
|
||||
try {
|
||||
FileOutputStream(tmp).use { it.write(value.toString().toByteArray(Charsets.UTF_8)); it.fd.sync() }
|
||||
replace(tmp, file)
|
||||
} finally { tmp.delete() }
|
||||
}
|
||||
|
||||
fun replace(from: File, to: File) {
|
||||
require(!Files.isSymbolicLink(to.toPath()))
|
||||
try { Files.move(from.toPath(), to.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
|
||||
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING) }
|
||||
}
|
||||
|
||||
fun hash(file: File, algorithm: String = "MD5"): String {
|
||||
val digest = MessageDigest.getInstance(algorithm)
|
||||
file.inputStream().use { input -> val buffer = ByteArray(128 * 1024); while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) } }
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
fun matches(folder: File, file: JSONObject): Boolean {
|
||||
val f = inside(folder, file.getString("path"))
|
||||
if (!Files.isRegularFile(f.toPath(), LinkOption.NOFOLLOW_LINKS) || f.length() != file.getLong("size")) return false
|
||||
val md5 = file.optString("md5")
|
||||
if (md5.matches(Regex("[a-fA-F0-9]{32}"))) return hash(f).equals(md5, true)
|
||||
val sha = file.optString("sha256")
|
||||
if (sha.isNotBlank()) return hash(f, "SHA-256").equals(sha, true)
|
||||
val chunks = file.optJSONArray("chunks")?.objects().orEmpty()
|
||||
var offset = 0L
|
||||
return chunks.isNotEmpty() && chunks.all { chunk ->
|
||||
val result = GogEstimate.range(f, offset, chunk.getLong("size"), chunk.getString("md5"))
|
||||
offset += chunk.getLong("size"); result
|
||||
} || f.length() == 0L
|
||||
}
|
||||
|
||||
fun validate(files: JSONArray, folder: File) {
|
||||
val paths = HashSet<String>()
|
||||
val components = HashMap<String, String>()
|
||||
for (file in files.objects()) {
|
||||
val path = file.getString("path").replace('\\', '/')
|
||||
inside(folder, path)
|
||||
require(!path.startsWith(".droiddeck-", true) && path != StoreGameSidecar.FILE_NAME) { "GOG content overlaps launcher metadata" }
|
||||
require(paths.add(path.lowercase(Locale.ROOT))) { "GOG paths differ only by case: $path" }
|
||||
var parent = folder
|
||||
var relative = ""
|
||||
for (part in path.split('/')) {
|
||||
relative = if (relative.isEmpty()) part else "$relative/$part"
|
||||
val previous = components.putIfAbsent(relative.lowercase(Locale.ROOT), relative)
|
||||
require(previous == null || previous == relative) { "GOG directory paths differ only by case: $path" }
|
||||
require(parent.list()?.none { it != part && it.equals(part, true) } != false) { "An existing path differs only by case: $path" }
|
||||
parent = File(parent, part)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun JSONArray.objects(): List<JSONObject> = (0 until length()).map { getJSONObject(it) }
|
||||
internal fun JSONArray.strings(): List<String> = (0 until length()).map { optString(it) }
|
||||
|
||||
internal data class GogBuild(val id: String, val version: String, val generation: Int, val branch: String, val link: String) {
|
||||
companion object {
|
||||
fun select(builds: JSONObject, pinned: String = "", branch: String = ""): GogBuild? {
|
||||
val items = builds.optJSONArray("items")?.objects().orEmpty().filter { it.optString("os", "windows") == "windows" }
|
||||
val item = if (pinned.isNotBlank()) items.firstOrNull { it.optString("build_id") == pinned || it.optString("legacy_build_id") == pinned }
|
||||
else items.firstOrNull { it.optString("branch").let { b -> (if (b == "null") "" else b) == branch } }
|
||||
return item?.let { GogBuild(it.optString("build_id"), it.optString("version_name"), it.optInt("generation", 2),
|
||||
it.optString("branch").let { b -> if (b == "null") "" else b },
|
||||
it.optString("link").ifBlank { it.optString("meta_url").ifBlank { it.optJSONArray("urls")?.optJSONObject(0)?.optString("url").orEmpty() } }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal data class GogOfflinePart(val id: String, val name: String, val url: String, val size: Long, val md5: String)
|
||||
internal data class GogOfflineDownload(val id: String, val name: String, val version: String, val language: String, val parts: List<GogOfflinePart>) {
|
||||
val size: Long get() = parts.sumOf { it.size }
|
||||
companion object {
|
||||
fun parse(downloads: JSONObject, kind: String): List<GogOfflineDownload> = downloads.optJSONArray(kind)?.objects().orEmpty()
|
||||
.filter { it.optString("os") == "windows" }.mapNotNull { entry ->
|
||||
val files = entry.optJSONArray("files")?.objects().orEmpty()
|
||||
val parts = files.mapNotNull { f ->
|
||||
val url = f.optString("downlink").ifBlank { f.optString("manualUrl") }
|
||||
if (url.isBlank()) null else GogOfflinePart(f.optString("id"), f.optString("filename"), url, f.optLong("size"), f.optString("md5"))
|
||||
}
|
||||
if (parts.isEmpty()) null else GogOfflineDownload(entry.optString("id").ifBlank { parts.first().id },
|
||||
entry.optString("name", "GOG download"), entry.optString("version"), entry.optString("language"), parts)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import com.droiddeck.launcher.agent.AgentGuest
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.*
|
||||
import com.droiddeck.launcher.stores.download.*
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal object GogMaintenance {
|
||||
enum class State { UNKNOWN, CHECKING, CURRENT, AVAILABLE, FAILED }
|
||||
data class Check(val state: State, val version: String = "", val reason: String = "")
|
||||
data class Proposal(val folder: File, val before: GogInstallRecord, val target: GogInstallRecord,
|
||||
val operation: GogOperation, val downloadBytes: Long, val diskBytes: Long, val patch: GogOfflineDownload? = null, val deltas: JSONArray = JSONArray(), val fullFiles: Boolean = false)
|
||||
|
||||
val checks = mutableStateMapOf<String, Check>()
|
||||
private val workers = Executors.newFixedThreadPool(2)
|
||||
private val checkedAt = java.util.concurrent.ConcurrentHashMap<String, Long>()
|
||||
private val inFlight = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
|
||||
@Volatile private var account = ""
|
||||
private val revision = java.util.concurrent.atomic.AtomicLong()
|
||||
private const val HELPER = "/usr/local/bin/droiddeck-gog-maintenance"
|
||||
const val OPERATION = "gogOperation"
|
||||
const val FOLDER = "gogFolder"
|
||||
|
||||
fun reset() {
|
||||
revision.incrementAndGet()
|
||||
account = ""; checkedAt.clear()
|
||||
StoresState.post { checks.clear() }
|
||||
}
|
||||
|
||||
fun checkInstalled(context: Context, games: List<InstalledStoreGame>) {
|
||||
val user = StoreAccounts.displayName(context, Store.GOG).orEmpty()
|
||||
if (user != account) { reset(); account = user }
|
||||
if (user.isBlank()) return
|
||||
games.filter { it.sidecar.store == Store.GOG && it.sidecar.isInstalled }.forEach { check(context, it) }
|
||||
}
|
||||
|
||||
fun check(context: Context, game: InstalledStoreGame, force: Boolean = false) {
|
||||
val key = game.folder.absolutePath
|
||||
if (!force && System.currentTimeMillis() - (checkedAt[key] ?: 0) < 30 * 60_000) return
|
||||
if (!inFlight.add(key)) return
|
||||
val owner = revision.get()
|
||||
StoresState.post { checks[game.sidecar.id] = Check(State.CHECKING) }
|
||||
workers.execute {
|
||||
val result = runCatching {
|
||||
var old = GogInstallRecord.migrate(game.folder, game.sidecar)
|
||||
if (!old.verified || GogFiles.journal(game.folder).exists()) Check(State.UNKNOWN, reason = "Finish or recover the GOG maintenance operation first")
|
||||
else {
|
||||
val token = GogContent.token(context)
|
||||
if (old.source == "depot") {
|
||||
val builds = GogContent.builds(old.id, token)
|
||||
if (old.files.length() == 0 && old.build.isNotBlank()) GogBuild.select(builds, pinned = old.build)?.let { old = old.copy(branch = it.branch, generation = it.generation) }
|
||||
val latest = GogBuild.select(builds, branch = old.branch)
|
||||
when { latest == null -> Check(State.UNKNOWN, reason = "No build is available on the installed branch")
|
||||
old.build.isBlank() -> Check(State.UNKNOWN, latest.version, "The installed build is unknown")
|
||||
latest.id == old.build -> Check(State.CURRENT, old.version)
|
||||
else -> Check(State.AVAILABLE, latest.version) }
|
||||
} else {
|
||||
val downloads = GogContent.product(old.id, token).getJSONObject("downloads")
|
||||
val installer = offlineInstaller(downloads, old.language)
|
||||
if (old.version.isBlank()) Check(State.UNKNOWN, installer.version, "The installed version is unknown")
|
||||
else Check(if (old.version == installer.version) State.CURRENT else State.AVAILABLE, installer.version)
|
||||
}
|
||||
}
|
||||
}.getOrElse { Check(State.FAILED, reason = it.message ?: "GOG update check failed") }
|
||||
if (revision.get() == owner && (result.state == State.CURRENT || result.state == State.AVAILABLE)) checkedAt[key] = System.currentTimeMillis()
|
||||
inFlight.remove(key)
|
||||
StoresState.post { if (revision.get() == owner) checks[game.sidecar.id] = result }
|
||||
}
|
||||
}
|
||||
|
||||
fun offlinePatches(context: Context, game: InstalledStoreGame): List<GogOfflineDownload> =
|
||||
GogOfflineDownload.parse(GogContent.product(game.sidecar.id, GogContent.token(context)).getJSONObject("downloads"), "patches")
|
||||
|
||||
internal fun offlineInstaller(downloads: JSONObject, language: String): GogOfflineDownload {
|
||||
val installers = GogOfflineDownload.parse(downloads, "installers")
|
||||
return installers.firstOrNull { it.language.equals(language, true) }
|
||||
?: installers.firstOrNull { !it.language.equals("Neutral", true) && StoreLanguage.depotAccepted(arrayOf(it.language), language) }
|
||||
?: installers.firstOrNull { it.language.equals("Neutral", true) }
|
||||
?: error("No Windows offline installer is available for the installed language ($language)")
|
||||
}
|
||||
|
||||
fun prepare(context: Context, game: InstalledStoreGame, operation: GogOperation, patch: GogOfflineDownload? = null, resume: Boolean = false): Proposal {
|
||||
val folder = game.folder.canonicalFile
|
||||
var old = GogInstallRecord.migrate(folder, game.sidecar)
|
||||
val journal = GogFiles.read(GogFiles.journal(folder))
|
||||
require(journal == null || journal.optString("folder") == folder.path) { "GOG recovery folder does not match" }
|
||||
if (journal != null && journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain") && operation != GogOperation.REFRESH) error("The patch was interrupted. Inspect the installer result or use a full offline refresh; it will not be rerun automatically.")
|
||||
require(journal == null || operation == GogOperation.REFRESH || journal.optString("operation") == operation.name) { "Resume the existing GOG operation or select a full offline refresh" }
|
||||
val token = GogContent.token(context)
|
||||
if (operation == GogOperation.PATCH) {
|
||||
if (old.source == "depot" && old.manifest.length() == 0 && old.build.isNotBlank()) {
|
||||
val exact = GogBuild.select(GogContent.builds(old.id, token), pinned = old.build)
|
||||
?: error("The installed GOG setup manifest is unavailable; use a full offline refresh")
|
||||
old = GogContent.snapshot(old, exact, token)
|
||||
}
|
||||
check(patch != null) { "Select a GOG patch" }
|
||||
if (resume) require(journal?.optString("downloadVersion") == patch.version) { "The selected patch changed; select it again in Offline patches" }
|
||||
val selected = GogContent.resolveDownload(patch, token)
|
||||
return Proposal(folder, old, old.copy(source = "offline", version = selected.version, verified = false), operation, selected.size,
|
||||
selected.size + folder.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.name != ".droiddeck-gog" }.filter { it.isFile }.sumOf { it.length() }, selected)
|
||||
}
|
||||
if (operation == GogOperation.REFRESH || old.source != "depot") {
|
||||
require(operation != GogOperation.REPAIR) { "This offline installation has no depot manifest. Use a full offline refresh to restore its files." }
|
||||
val download = GogContent.resolveDownload(offlineInstaller(GogContent.product(old.id, token).getJSONObject("downloads"), old.language), token)
|
||||
if (resume) require(journal?.optString("downloadId") == download.id && journal.optString("downloadVersion") == download.version) { "The previous offline installer is no longer available; select a new full offline refresh" }
|
||||
if (old.products.any { it != old.id }) {
|
||||
val pinned = journal?.optJSONObject("target")?.optString("build").orEmpty()
|
||||
val build = GogBuild.select(GogContent.builds(old.id, token), pinned = pinned, branch = old.branch)
|
||||
?: error("No depot build is available to preserve installed DLC during this refresh. Use Update instead.")
|
||||
val target = GogContent.snapshot(old, build, token)
|
||||
GogFiles.validate(target.files, folder)
|
||||
val native = GogNative.isAvailable()
|
||||
val remaining = GogEstimate.calculate(folder, old, target, JSONArray(), reuseChunks = native)
|
||||
return Proposal(folder, old, target, GogOperation.REFRESH, Math.addExact(download.size, remaining.download),
|
||||
Math.addExact(Math.multiplyExact(download.size, 3), remaining.required), download, fullFiles = !native)
|
||||
}
|
||||
val target = old.copy(source = "offline", build = "", generation = 0, version = download.version, manifest = JSONObject(), files = JSONArray(), verified = true)
|
||||
return Proposal(folder, old, target, GogOperation.REFRESH, download.size, download.size * 3, download)
|
||||
}
|
||||
require(old.verified || operation != GogOperation.REPAIR) { "The patched installation must be reconciled before repair" }
|
||||
val pinned = journal?.optJSONObject("target")?.let(GogInstallRecord::parse)
|
||||
val builds = GogContent.builds(old.id, token)
|
||||
if (old.files.length() == 0 && old.build.isNotBlank()) GogBuild.select(builds, pinned = old.build)?.let { old = old.copy(branch = it.branch, generation = it.generation) }
|
||||
val build = GogBuild.select(builds,
|
||||
pinned = pinned?.build ?: if (operation == GogOperation.REPAIR) old.build.ifBlank { error("The installed GOG build is unknown; update it first") } else "",
|
||||
branch = pinned?.branch ?: old.branch) ?: error("The requested GOG build is no longer available")
|
||||
val target = GogContent.snapshot(old, build, token)
|
||||
GogFiles.validate(target.files, folder)
|
||||
var before = journal?.optJSONObject("before")?.let(GogInstallRecord::parse) ?: old
|
||||
if (before.files.length() == 0 && before.build.isNotBlank()) {
|
||||
val historical = GogBuild.select(builds, pinned = before.build)
|
||||
if (historical != null) before = runCatching { GogContent.snapshot(before, historical, token) }.getOrDefault(before)
|
||||
}
|
||||
val deltas = GogContent.patches(before, target, token)
|
||||
val native = GogNative.isAvailable()
|
||||
val size = GogEstimate.calculate(folder, before, target, deltas, reuseChunks = native)
|
||||
return Proposal(folder, before, target, operation, size.download, size.required, deltas = deltas, fullFiles = !native)
|
||||
}
|
||||
|
||||
fun resume(context: Context, game: InstalledStoreGame): Proposal {
|
||||
val journal = GogFiles.read(GogFiles.journal(game.folder)) ?: error("GOG operation journal is missing")
|
||||
val operation = GogOperation.valueOf(journal.getString("operation"))
|
||||
val patch = if (operation == GogOperation.PATCH) offlinePatches(context, game)
|
||||
.firstOrNull { it.id == journal.optString("downloadId") } ?: error("The selected GOG patch is no longer available") else null
|
||||
return prepare(context, game, operation, patch, resume = true)
|
||||
}
|
||||
|
||||
fun recoverPatch(context: Context, game: InstalledStoreGame) {
|
||||
val folder = game.folder.canonicalFile
|
||||
check(!DownloadQueue.isActive(game.key)) { "Wait for the GOG operation to finish" }
|
||||
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG patch journal is missing")
|
||||
require(journal.optString("folder") == folder.path && journal.optString("operation") == GogOperation.PATCH.name)
|
||||
require(journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain"))
|
||||
RandomAccessFile(GogFiles.inside(folder, ".droiddeck-gog/lease"), "rw").use { lease ->
|
||||
val lock = runCatching { lease.channel.tryLock() }.getOrNull() ?: error("Close the patch installer before verifying its result")
|
||||
lock.use {
|
||||
ensureIdle(context, folder)
|
||||
val before = GogInstallRecord.parse(journal.getJSONObject("before"))
|
||||
val buildId = GogInstallRecord.authenticBuild(folder, before.id).ifBlank { before.build }
|
||||
check(buildId.isNotBlank()) { "The resulting build is unknown. Use a full offline refresh." }
|
||||
val token = GogContent.token(context)
|
||||
val build = GogBuild.select(GogContent.builds(before.id, token), pinned = buildId)
|
||||
?: error("The resulting build manifest is unavailable. Use a full offline refresh.")
|
||||
val target = GogContent.snapshot(before, build, token)
|
||||
GogFiles.validate(target.files, folder)
|
||||
check(target.files.objects().all { it.optBoolean("directory") || GogFiles.matches(folder, it) }) {
|
||||
"The files do not match the reported build. Use a full offline refresh to recover."
|
||||
}
|
||||
val sidecar = StoreGameSidecar.parse(journal.getJSONObject("sidecar").toString()) ?: error("The original GOG settings are missing")
|
||||
target.write(folder)
|
||||
StoreInstalls.complete(context, folder, sidecar.copy(installVersion = target.build, state = StoreGameSidecar.STATE_INSTALLED))
|
||||
check(GogFiles.journal(folder).delete()) { "Could not finish the GOG recovery record" }
|
||||
}
|
||||
}
|
||||
checkedAt.remove(folder.path)
|
||||
DownloadQueue.dismiss(game.key)
|
||||
StoresState.notifyLibraryChanged(context)
|
||||
StoresState.post { checks.remove(game.sidecar.id) }
|
||||
}
|
||||
|
||||
fun enqueue(context: Context, game: InstalledStoreGame, proposal: Proposal) {
|
||||
val app = context.applicationContext
|
||||
require(game.folder.canonicalFile == proposal.folder)
|
||||
check(!DownloadQueue.isActive("gog:${game.sidecar.id}")) { "GOG maintenance is already queued" }
|
||||
check(!StoreInstallRoot.insufficientSpace(proposal.diskBytes, StoreInstallRoot.availableBytes(proposal.folder))) { "Not enough free space for GOG maintenance" }
|
||||
val journal = JSONObject().put("schema", 1).put("folder", proposal.folder.path).put("operation", proposal.operation.name)
|
||||
.put("before", proposal.before.json()).put("target", proposal.target.json()).put("sidecar", game.sidecar.toJson()).put("phase", "download")
|
||||
proposal.patch?.let { journal.put("downloadId", it.id).put("downloadVersion", it.version) }
|
||||
GogFiles.write(GogFiles.journal(proposal.folder), journal)
|
||||
val item = CatalogItem(Store.GOG, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover,
|
||||
extra = mapOf(OPERATION to proposal.operation.name, FOLDER to proposal.folder.path))
|
||||
SavedQueue.remember(app, item, null)
|
||||
enqueueJob(app, item, proposal)
|
||||
}
|
||||
|
||||
private fun enqueueJob(context: Context, item: CatalogItem, proposal: Proposal) {
|
||||
DownloadQueue.enqueue(context, DownloadEntry(Store.GOG, item.id, item.title, cover = item.tallImageUrl,
|
||||
bytesTotal = proposal.downloadBytes, location = StoreInstallRoot.labelFor(context, proposal.folder))) { Job(context, proposal) }
|
||||
}
|
||||
|
||||
fun restore(context: Context, item: CatalogItem) {
|
||||
val folder = File(item.extra[FOLDER] ?: error("Missing GOG recovery folder")).canonicalFile
|
||||
require(StoreInstallRoot.gameFolders(context).any { it.canonicalFile == folder }) { "GOG recovery folder is unavailable" }
|
||||
val sidecar = StoreGameSidecar.read(folder) ?: error("GOG installation record is missing")
|
||||
require(sidecar.store == Store.GOG && sidecar.id == item.id)
|
||||
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG operation journal is missing")
|
||||
val operation = GogOperation.valueOf(journal.getString("operation"))
|
||||
if (journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain")) {
|
||||
DownloadQueue.recordFailed(context, DownloadEntry(Store.GOG, item.id, item.title), "The patch result needs recovery; open Offline patches")
|
||||
return
|
||||
}
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
SavedQueue.remember(context, item, null)
|
||||
enqueueJob(context, item, resume(context, game))
|
||||
}
|
||||
|
||||
private class Job(val app: Context, val proposal: Proposal) : DownloadQueue.DownloadJob {
|
||||
val cancelled = AtomicBoolean(false)
|
||||
@Volatile var applyingPatch = false
|
||||
@Volatile private var running = false
|
||||
@Volatile private var deleteCaches = false
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
if (applyingPatch) return
|
||||
deleteCaches = deleteCaches || deleteFiles
|
||||
cancelled.set(true)
|
||||
if (!running && deleteCaches) cleanCaches()
|
||||
}
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
running = true
|
||||
try { return perform(handle) }
|
||||
finally {
|
||||
running = false; applyingPatch = false; handle.interruptible(true)
|
||||
if (deleteCaches) cleanCaches()
|
||||
}
|
||||
}
|
||||
|
||||
private fun cleanCaches() {
|
||||
for (name in listOf("stage", "downloads", "extracted")) {
|
||||
val root = GogFiles.inside(proposal.folder, ".droiddeck-gog/$name")
|
||||
if (root.exists()) java.nio.file.Files.walk(root.toPath()).use { paths ->
|
||||
paths.sorted(java.util.Comparator.reverseOrder()).forEach { java.nio.file.Files.deleteIfExists(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun perform(handle: DownloadQueue.JobHandle): String? {
|
||||
val folder = proposal.folder
|
||||
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG operation journal is missing")
|
||||
val sidecar = StoreGameSidecar.parse(journal.getJSONObject("sidecar").toString()) ?: error("GOG previous installation is missing")
|
||||
if (proposal.operation == GogOperation.PATCH) {
|
||||
val result = GogOffline.apply(app, proposal, handle, cancelled, onApplying = { applyingPatch = true; handle.interruptible(false) })
|
||||
applyingPatch = false; handle.interruptible(true)
|
||||
if (!result || cancelled.get()) return null
|
||||
} else {
|
||||
RandomAccessFile(GogFiles.inside(folder, ".droiddeck-gog/lease"), "rw").use { lease ->
|
||||
val lock = runCatching { lease.channel.tryLock() }.getOrNull() ?: error("Close the GOG game before updating it")
|
||||
lock.use {
|
||||
ensureIdle(app, folder)
|
||||
sidecar.copy(state = StoreGameSidecar.STATE_UPDATING).write(folder)
|
||||
GogFiles.write(GogFiles.journal(folder), journal.put("phase", "applying"))
|
||||
if (proposal.operation == GogOperation.REFRESH) {
|
||||
GogOffline.refresh(app, proposal, handle, cancelled)
|
||||
if (!cancelled.get() && proposal.target.source == "depot") transfer(app, proposal, handle, cancelled)
|
||||
} else transfer(app, proposal, handle, cancelled)
|
||||
if (cancelled.get()) return null
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cancelled.get()) return null
|
||||
val target = GogInstallRecord.read(folder)?.takeIf { proposal.operation == GogOperation.PATCH || proposal.operation == GogOperation.REFRESH && proposal.target.source != "depot" } ?: proposal.target
|
||||
check(target.verified) { "The patch completed, but its resulting version could not be verified. Inspect the game or use a full offline refresh." }
|
||||
target.write(folder)
|
||||
StoreInstalls.complete(app, folder, sidecar.copy(installVersion = target.build.ifBlank { target.version }, state = StoreGameSidecar.STATE_INSTALLED))
|
||||
check(GogFiles.journal(folder).delete()) { "Could not finish the GOG recovery record" }
|
||||
runCatching { cleanCaches() }.onFailure { handle.log("gog: completed; could not remove expendable cache: ${it.message}") }
|
||||
checkedAt.remove(folder.path)
|
||||
StoresState.post { checks.remove(sidecar.id) }
|
||||
return folder.path
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureIdle(context: Context, folder: File) {
|
||||
val game = AddedGames.single(context, folder.path) ?: return
|
||||
check(SessionState.gameId != (game.appId and 0xffffffffL).toString()) { "Close the GOG game before maintenance" }
|
||||
if (SessionState.running) {
|
||||
val id = (game.steamAppId?.toLong() ?: game.appId) and 0xffffffffL
|
||||
val guest = AddedGames.guestPath(context, folder) ?: error("The GOG folder is unavailable to Linux")
|
||||
if (SessionState.suspended || AgentGuest.hello(context) == null) {
|
||||
val root = AddedGames.guestPath(context, SessionPrefs.activeSteamRoot(context)) ?: error("The Steam folder is unavailable to Linux")
|
||||
val rc = GuestCommand.run(context, listOf("/usr/bin/env", "STEAM_COMPAT_CLIENT_INSTALL_PATH=$root", HELPER, "idle", guest, id.toString(), game.guestExe),
|
||||
extraBinds = StoreInstallRoot.externalBindSpecs(context), logName = "gog-idle", onLine = StoresState::logLine)
|
||||
check(rc == 0) { "Close the GOG game before maintenance" }
|
||||
return
|
||||
}
|
||||
val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, "idle", guest, id.toString(), game.guestExe))).put("timeout", 15)
|
||||
val result = AgentGuest.call(context, request, 20_000, trusted = true)
|
||||
check(result.optBoolean("ok") && result.optInt("exitCode", -1) == 0) { "Close the GOG game before maintenance" }
|
||||
}
|
||||
}
|
||||
|
||||
private fun transfer(context: Context, proposal: Proposal, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean, callback: GogDownloadManager.Callback? = null) {
|
||||
val token = GogContent.token(context)
|
||||
var patches = proposal.deltas
|
||||
var previousWire = 0L
|
||||
for (attempt in 0..4) {
|
||||
if (stop.get()) return
|
||||
val links = GogContent.links(proposal.target, GogContent.token(context))
|
||||
val patchLinks = if (patches.length() > 0) runCatching { GogContent.links(proposal.target, token, patches = true) }.getOrElse { patches = JSONArray(); JSONObject() } else JSONObject()
|
||||
val plan = JSONObject().put("files", proposal.target.files).put("oldFiles", proposal.before.files)
|
||||
.put("patches", patches).put("links", links).put("patchLinks", patchLinks).put("downloadBytes", proposal.downloadBytes)
|
||||
val optimized = GogNative.isAvailable()
|
||||
val remaining = GogEstimate.calculate(proposal.folder, proposal.before, proposal.target, patches, reuseChunks = optimized).required
|
||||
check(!StoreInstallRoot.insufficientSpace(remaining, StoreInstallRoot.availableBytes(proposal.folder))) { "Not enough free space for remaining GOG maintenance" }
|
||||
handle?.diskSize(remaining)
|
||||
if (!optimized) {
|
||||
try { GogFallback.transfer(proposal.folder, plan, handle, stop, callback); return }
|
||||
catch (e: Exception) {
|
||||
if (stop.get()) return
|
||||
if (attempt == 4 || Regex("HTTP (401|403|404|500)").find(e.message.orEmpty()) == null) throw e
|
||||
handle?.log("gog: refreshing file-download links; verified replacements are retained")
|
||||
continue
|
||||
}
|
||||
}
|
||||
val latch = CountDownLatch(1)
|
||||
var runWire = 0L
|
||||
var success = false; var expired = false; var failure = "GOG download failed"
|
||||
val listener = object : GogNative.Listener {
|
||||
override fun onProgress(bytesDone: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, file: String, fileBytes: Long, verified: Boolean) {
|
||||
handle?.stage(if (verified) DownloadStage.VERIFY else DownloadStage.INSTALL)
|
||||
handle?.stageProgress(filesDone.toLong(), filesTotal.toLong(), filesDone, filesTotal)
|
||||
callback?.onStage(if (verified) "verify" else "install", filesDone.toLong(), filesTotal.toLong(), filesDone, filesTotal)
|
||||
}
|
||||
override fun onBytes(bytesDone: Long, bytesTotal: Long) {
|
||||
runWire = bytesDone
|
||||
handle?.progress(previousWire + bytesDone, (previousWire + bytesTotal).coerceAtLeast(previousWire + bytesDone))
|
||||
callback?.onBytes(previousWire + bytesDone, (previousWire + bytesTotal).coerceAtLeast(previousWire + bytesDone), 0)
|
||||
}
|
||||
override fun onLog(line: String) { handle?.log(line); callback?.onLog(line) }
|
||||
override fun onMaintenance(networkBytes: Long, reusedBytes: Long, appliedBytes: Long) { handle?.maintenance(reusedBytes, appliedBytes) }
|
||||
override fun onComplete(ok: Boolean, cancelled: Boolean, linkExpiry: Boolean, error: String, bytesWritten: Long, filesDone: Int) {
|
||||
success = ok; expired = linkExpiry; failure = error; latch.countDown()
|
||||
}
|
||||
}
|
||||
val native = GogNative.start(2, arrayOf(plan.toString()), emptyArray(), proposal.folder.path, emptyArray(), "", 1, 1, false, "gog maintenance", listener)
|
||||
check(native != 0L) { "GOG native engine could not start" }
|
||||
try { while (!latch.await(200, TimeUnit.MILLISECONDS)) if (stop.get()) GogNative.cancel(native) }
|
||||
finally { GogNative.release(native) }
|
||||
if (stop.get()) return
|
||||
if (success) {
|
||||
for (file in proposal.target.files.objects()) if (!file.optBoolean("directory") && file.optString("md5").isBlank() && file.optString("sha256").isBlank())
|
||||
file.put("sha256", GogFiles.hash(GogFiles.inside(proposal.folder, file.getString("path")), "SHA-256"))
|
||||
return
|
||||
}
|
||||
if (!expired || attempt == 4) error(failure)
|
||||
previousWire += runWire
|
||||
handle?.log("gog: refreshing expired download links; validated files and chunks are retained")
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun installContent(context: Context, game: GogGame, folder: File, builds: JSONObject, language: String,
|
||||
callback: GogDownloadManager.Callback, cancelled: AtomicBoolean): GogDownloadManager.Result? {
|
||||
val build = GogBuild.select(builds) ?: return null
|
||||
folder.mkdirs()
|
||||
val old = GogInstallRecord(game.gameId, "depot", language = language)
|
||||
val target = GogContent.snapshot(old, build, GogContent.token(context))
|
||||
GogFiles.validate(target.files, folder)
|
||||
val bytes = target.files.objects().sumOf { it.optJSONArray("chunks")?.objects()?.sumOf { c -> c.optLong("compressedSize") }?.takeIf { n -> n > 0 } ?: it.optLong("size") }
|
||||
val disk = target.files.objects().sumOf { it.optLong("size") }
|
||||
check(!StoreInstallRoot.insufficientSpace(disk, StoreInstallRoot.availableBytes(folder))) { "Not enough free space for GOG installation" }
|
||||
callback.onSizes(bytes, disk)
|
||||
transfer(context, Proposal(folder, old, target, GogOperation.UPDATE, bytes, disk), null, cancelled, callback)
|
||||
if (cancelled.get()) return null
|
||||
target.write(folder)
|
||||
val result = GogDownloadManager.Result(GogDownloadManager.pickExe(folder, null, game.title), build.id, disk)
|
||||
result.language = target.language
|
||||
result.dependencies = target.manifest.optJSONArray("dependencies")?.strings().orEmpty()
|
||||
result.dependenciesRead = true
|
||||
return result
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun captureDepot(id: String, folder: File, build: String, buildsJson: String, manifest: JSONObject, depots: JSONArray, language: String) {
|
||||
val selected = GogBuild.select(JSONObject(buildsJson), pinned = build)
|
||||
val files = JSONArray()
|
||||
for (depot in depots.strings()) for (item in JSONObject(depot).getJSONObject("depot").getJSONArray("items").objects()) {
|
||||
val chunks = item.optJSONArray("chunks") ?: continue
|
||||
files.put(JSONObject().put("path", item.getString("path").replace('\\', '/')).put("size", chunks.objects().sumOf { it.optLong("size") })
|
||||
.put("md5", item.optString("md5")).put("chunks", chunks).put("product", id))
|
||||
}
|
||||
GogFiles.validate(files, folder)
|
||||
GogInstallRecord(id, "depot", 2, build, selected?.version.orEmpty(), selected?.branch.orEmpty(), language,
|
||||
manifest = GogContent.sanitize(manifest), files = files).write(folder)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun captureOffline(id: String, folder: File, downloads: JSONObject) {
|
||||
val selected = GogOfflineDownload.parse(downloads, "installers").firstOrNull() ?: return
|
||||
GogInstallRecord(id, "offline", version = selected.version, language = selected.language).write(folder)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ object GogNative {
|
||||
|
||||
fun onBytes(bytesDone: Long, bytesTotal: Long)
|
||||
|
||||
fun onMaintenance(networkBytes: Long, reusedBytes: Long, appliedBytes: Long)
|
||||
|
||||
fun onLog(line: String)
|
||||
|
||||
fun onComplete(success: Boolean, cancelled: Boolean, linkExpiry: Boolean, error: String, bytesWritten: Long, filesDone: Int)
|
||||
@@ -26,7 +28,7 @@ object GogNative {
|
||||
fun isAvailable(): Boolean {
|
||||
available?.let { return it }
|
||||
val ok = try {
|
||||
StoresNative.ensureLoaded() && nativeProbe() == 1
|
||||
StoresNative.ensureLoaded() && nativeProbe() == 2
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "native GOG engine unavailable: ${t.javaClass.simpleName}: ${t.message}")
|
||||
false
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.agent.AgentGuest
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal object GogOffline {
|
||||
private const val HELPER = "/usr/local/bin/droiddeck-gog-maintenance"
|
||||
|
||||
internal data class Layout(val source: File, val prefix: String)
|
||||
|
||||
internal fun layout(extracted: File, installed: File, id: String, executable: String): Layout {
|
||||
val nested = executable.startsWith("app/", true) && !File(installed, "goggame-$id.info").isFile
|
||||
return Layout(extracted, if (nested) "app/" else "")
|
||||
}
|
||||
|
||||
internal fun validateDepotInstaller(extracted: File, target: GogInstallRecord) {
|
||||
if (target.source != "depot") return
|
||||
val builds = listOf(extracted, File(extracted, "app")).map { GogInstallRecord.authenticBuild(it, target.id) }.filter { it.isNotBlank() }
|
||||
require(builds.isNotEmpty() && builds.all { it == target.build } && target.build.isNotBlank()) {
|
||||
"The offline installer does not identify the selected depot build. Use Update to preserve installed DLC."
|
||||
}
|
||||
}
|
||||
|
||||
private fun download(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean): File {
|
||||
val patch = proposal.patch ?: error("GOG download selection is missing")
|
||||
val root = File(GogFiles.dir(proposal.folder), "downloads").apply { mkdirs() }
|
||||
var first: File? = null; var bytes = 0L
|
||||
for ((index, part) in patch.parts.withIndex()) {
|
||||
if (stop.get()) return first ?: File(root, "cancelled")
|
||||
val resolved = GogDownloadManager.resolveRedirect(part.url, GogContent.token(context)) ?: error("The GOG download link is unavailable")
|
||||
val serverName = GogContent.downloadFilename(resolved).takeIf { it.endsWith(".exe", true) || it.endsWith(".bin", true) }
|
||||
val name = part.name.ifBlank { serverName ?: error("GOG did not provide the installer part filename") }
|
||||
require('/' !in name && '\\' !in name && name !in setOf(".", "..")) { "Invalid GOG installer filename" }
|
||||
val file = GogFiles.inside(root, name)
|
||||
val receipt = File(root, "part-$index.json")
|
||||
val saved = GogFiles.read(receipt)
|
||||
val complete = file.isFile && (part.size <= 0 || file.length() == part.size) && when {
|
||||
part.md5.isNotBlank() -> GogFiles.hash(file).equals(part.md5, true)
|
||||
saved?.optString("id") == part.id && saved.optString("filename") == name -> GogFiles.hash(file, "SHA-256") == saved.optString("sha256")
|
||||
else -> false
|
||||
}
|
||||
if (!complete) {
|
||||
val staging = GogFiles.inside(root, "$name.partial")
|
||||
GogFallback.download(listOf(resolved), staging, part.size, stop, { n -> bytes += n; handle.progress(bytes, proposal.downloadBytes.coerceAtLeast(bytes)) })
|
||||
if (stop.get()) return first ?: file
|
||||
if (part.md5.isNotBlank()) check(GogFiles.hash(staging).equals(part.md5, true)) { "GOG installer checksum mismatch" }
|
||||
GogFiles.replace(staging, file)
|
||||
GogFiles.write(receipt, JSONObject().put("id", part.id).put("filename", name).put("sha256", GogFiles.hash(file, "SHA-256")))
|
||||
}
|
||||
if (index == 0) { check(file.extension.equals("exe", true)) { "GOG patch has no setup executable" }; first = file }
|
||||
}
|
||||
return first ?: error("GOG download has no files")
|
||||
}
|
||||
|
||||
fun refresh(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean) {
|
||||
val installer = download(context, proposal, handle, stop)
|
||||
if (stop.get()) return
|
||||
val extracted = File(GogFiles.dir(proposal.folder), "extracted").apply { mkdirs() }
|
||||
val source = AddedGames.guestPath(context, installer) ?: error("The GOG installer is not visible to Linux")
|
||||
val target = AddedGames.guestPath(context, extracted) ?: error("The GOG staging folder is not visible to Linux")
|
||||
handle.stage(DownloadStage.INSTALL, "Extracting the full offline installer")
|
||||
val rc = GuestCommand.run(context, listOf("/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", target, source),
|
||||
extraBinds = StoreInstallRoot.externalBindSpecs(context), cancelled = stop, logName = "gog-refresh", onLine = handle::log)
|
||||
if (stop.get()) return
|
||||
check(rc == 0) { "GOG installer extraction failed (exit $rc)" }
|
||||
applyRefresh(proposal, extracted, handle, stop)
|
||||
}
|
||||
|
||||
internal fun applyRefresh(proposal: GogMaintenance.Proposal, extracted: File, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean) {
|
||||
validateDepotInstaller(extracted, proposal.target)
|
||||
val sidecar = StoreGameSidecar.read(proposal.folder) ?: error("The original GOG settings are missing")
|
||||
val layout = layout(extracted, proposal.folder, proposal.before.id, sidecar.exe)
|
||||
val files = layout.source.walkTopDown().onEnter { directory ->
|
||||
check(!java.nio.file.Files.isSymbolicLink(directory.toPath())) { "GOG installer contains a symbolic link" }
|
||||
directory.parentFile != extracted || directory.name !in setOf("tmp", "commonappdata", "userappdata", "localappdata")
|
||||
}.filter { it != layout.source && it != File(extracted, "app") }.map { file ->
|
||||
check(!java.nio.file.Files.isSymbolicLink(file.toPath()))
|
||||
val relative = file.relativeTo(layout.source).invariantSeparatorsPath.removePrefix("app/")
|
||||
JSONObject().put("path", layout.prefix + relative)
|
||||
.put("size", if (file.isDirectory) 0 else file.length()).put("directory", file.isDirectory)
|
||||
.put("md5", if (file.isDirectory) "" else GogFiles.hash(file)).put("product", proposal.before.id) to file
|
||||
}.toList().groupBy { it.first.getString("path") }.map { (_, entries) ->
|
||||
check(entries.size == 1 || entries.all { it.first.getBoolean("directory") }) { "GOG installer has conflicting file locations" }
|
||||
entries.first()
|
||||
}
|
||||
check(files.any { !it.first.getBoolean("directory") }) { "GOG installer contained no game files" }
|
||||
val inventory = JSONArray(files.map { it.first })
|
||||
GogFiles.validate(inventory, proposal.folder)
|
||||
val executable = sidecar.exe.replace('\\', '/')
|
||||
check(files.any { !it.first.getBoolean("directory") && it.first.getString("path").equals(executable, true) } ||
|
||||
proposal.before.verified && proposal.before.files.length() > 0 &&
|
||||
proposal.before.files.objects().none { it.getString("path").equals(executable, true) } && GogFiles.inside(proposal.folder, executable).isFile) {
|
||||
"The offline installer did not extract the game's executable. No installed files were changed."
|
||||
}
|
||||
val installed = proposal.target.copy(files = inventory)
|
||||
GogFiles.write(File(GogFiles.dir(proposal.folder), "refresh-target.json"), installed.json())
|
||||
for ((index, entry) in files.withIndex()) {
|
||||
if (stop.get()) return
|
||||
val (file, sourceFile) = entry
|
||||
val destination = GogFiles.inside(proposal.folder, file.getString("path"))
|
||||
if (file.getBoolean("directory")) java.nio.file.Files.createDirectories(destination.toPath()) else {
|
||||
destination.parentFile!!.mkdirs()
|
||||
GogFiles.replace(sourceFile, destination)
|
||||
}
|
||||
handle?.stageProgress((index + 1).toLong(), files.size.toLong())
|
||||
}
|
||||
if (proposal.target.source != "depot") {
|
||||
val targetPaths = files.mapTo(HashSet()) { it.first.getString("path").lowercase(java.util.Locale.ROOT) }
|
||||
for (old in proposal.before.files.objects()) if (old.getString("path").lowercase(java.util.Locale.ROOT) !in targetPaths && GogFiles.matches(proposal.folder, old))
|
||||
check(GogFiles.inside(proposal.folder, old.getString("path")).delete())
|
||||
installed.write(proposal.folder)
|
||||
}
|
||||
}
|
||||
|
||||
fun apply(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean, onApplying: () -> Unit): Boolean {
|
||||
check(GogFiles.read(GogFiles.journal(proposal.folder))?.optString("phase") in setOf("download", "patch-ready")) {
|
||||
"The patch result needs recovery. Inspect the installer or use a full offline refresh; the patch will not be run again."
|
||||
}
|
||||
val installer = download(context, proposal, handle, stop)
|
||||
if (stop.get()) return false
|
||||
val setup = GogContent.setupFiles(proposal.before, GogContent.token(context))
|
||||
if (setup != null) {
|
||||
GogFallback.transfer(proposal.folder, JSONObject().put("files", setup.first).put("links", setup.second)
|
||||
.put("downloadBytes", setup.first.objects().sumOf { it.getJSONArray("chunks").objects().sumOf { chunk -> chunk.getLong("compressedSize") } }), handle, stop)
|
||||
if (stop.get()) return false
|
||||
}
|
||||
val added = AddedGames.single(context, proposal.folder.path) ?: error("The GOG game shortcut is unavailable")
|
||||
val id = (added.steamAppId?.toLong() ?: added.appId) and 0xffffffffL
|
||||
val folder = AddedGames.guestPath(context, proposal.folder) ?: error("The GOG folder is unavailable to Linux")
|
||||
val executable = AddedGames.guestPath(context, installer) ?: error("The GOG patch is unavailable to Linux")
|
||||
context.startActivity(android.content.Intent(context, com.droiddeck.launcher.SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, if (SessionState.running) SessionState.mode else SessionService.MODE_DESKTOP)
|
||||
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP or android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
||||
val deadline = System.currentTimeMillis() + 120_000
|
||||
while (AgentGuest.hello(context) == null && System.currentTimeMillis() < deadline) { if (stop.get()) return false; Thread.sleep(250) }
|
||||
check(AgentGuest.hello(context) != null) { "The Linux session did not become ready; open it and retry" }
|
||||
val journal = GogFiles.read(GogFiles.journal(proposal.folder)) ?: error("GOG patch journal is missing")
|
||||
journal.put("phase", "patch-ready")
|
||||
File(GogFiles.dir(proposal.folder), "patch-status.json").delete()
|
||||
GogFiles.write(GogFiles.journal(proposal.folder), journal)
|
||||
val request = JSONObject().put("kind", "exec").put("timeout", 15)
|
||||
.put("env", JSONObject().put("DROIDDECK_GOG_DESKTOP", if (SessionState.mode == SessionService.MODE_DESKTOP) "1" else "0"))
|
||||
.put("argv", JSONArray(listOf(HELPER, "start", folder, id.toString(), executable, added.guestExe)))
|
||||
if (stop.get()) return false
|
||||
onApplying()
|
||||
val response = AgentGuest.call(context, request, 20_000, trusted = true)
|
||||
check(response.optBoolean("ok") && response.optInt("exitCode", -1) == 0) { "The GOG patch installer could not start; inspect the GOG log" }
|
||||
handle.stage(DownloadStage.INSTALL, "Use the Linux session to finish or cancel the patch installer")
|
||||
var nextStatus = System.currentTimeMillis() + 5_000
|
||||
while (true) {
|
||||
val status = GogFiles.read(File(GogFiles.dir(proposal.folder), "patch-status.json"))
|
||||
if (status?.optString("state") in setOf("done", "failed", "uncertain")) {
|
||||
check(status?.optString("state") == "done") { status?.optString("reason") ?: "GOG patch failed" }
|
||||
break
|
||||
}
|
||||
check(SessionState.running) { "The patch session ended. Its result needs recovery; the patch will not be rerun automatically." }
|
||||
check(!SessionState.suspended) { "The patch session was suspended. Resume it and verify recovery before retrying." }
|
||||
if (System.currentTimeMillis() >= nextStatus) {
|
||||
val query = JSONObject().put("kind", "exec").put("timeout", 5).put("argv", JSONArray(listOf(HELPER, "status", folder)))
|
||||
val answer = AgentGuest.call(context, query, 10_000, trusted = true)
|
||||
check(answer.optBoolean("ok") && answer.optInt("exitCode", -1) == 0) { "The patch helper could not be reached. Resume the Linux session and verify recovery." }
|
||||
nextStatus = System.currentTimeMillis() + 5_000
|
||||
}
|
||||
Thread.sleep(500)
|
||||
}
|
||||
val info = GogFiles.read(File(proposal.folder, "goggame-${proposal.before.id}.info"))
|
||||
val version = info?.optString("versionName").orEmpty()
|
||||
val build = GogInstallRecord.authenticBuild(proposal.folder, proposal.before.id)
|
||||
var record = proposal.target.copy(build = build, version = version, files = JSONArray(), manifest = JSONObject(), verified = false)
|
||||
record.write(proposal.folder)
|
||||
if (build.isNotBlank()) {
|
||||
record = runCatching {
|
||||
val token = GogContent.token(context)
|
||||
val target = GogBuild.select(GogContent.builds(record.id, token), pinned = build)
|
||||
val snapshot = target?.let { GogContent.snapshot(record, it, token) }
|
||||
snapshot?.takeIf { it.files.objects().all { f -> f.optBoolean("directory") || GogFiles.matches(proposal.folder, f) } } ?: record
|
||||
}.getOrDefault(record)
|
||||
}
|
||||
record.write(proposal.folder)
|
||||
if (!record.verified) {
|
||||
val before = StoreGameSidecar.read(proposal.folder) ?: error("The GOG installation record is missing")
|
||||
before.copy(installVersion = "", state = StoreGameSidecar.STATE_UPDATING).write(proposal.folder)
|
||||
val operation = GogFiles.read(GogFiles.journal(proposal.folder))!!
|
||||
GogFiles.write(GogFiles.journal(proposal.folder), operation.put("phase", "patch-uncertain"))
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -351,7 +351,7 @@ internal fun GameActions(
|
||||
val gone = storeKey?.let { StoresState.uninstalling[it] }
|
||||
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
|
||||
PrimaryButton(
|
||||
stringResource(R.string.stores_play), enabled = !s.busy && gone == null && download == null && !xboxBusy,
|
||||
stringResource(R.string.stores_play), enabled = !s.busy && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
|
||||
main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn,
|
||||
) {
|
||||
if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(ctx, store, id, s, a)
|
||||
@@ -363,6 +363,7 @@ internal fun GameActions(
|
||||
EditArtButton(game)
|
||||
}
|
||||
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
|
||||
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
|
||||
if (store == Store.XBOX && installed != null && id != null) {
|
||||
SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import com.droiddeck.launcher.stores.gog.*
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@Composable
|
||||
internal fun GogMaintenanceActions(game: InstalledStoreGame) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val scope = rememberCoroutineScope()
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var patches by remember { mutableStateOf<List<GogOfflineDownload>?>(null) }
|
||||
var proposal by remember { mutableStateOf<GogMaintenance.Proposal?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var recoverablePatch by remember { mutableStateOf(false) }
|
||||
val key = "gog:${game.sidecar.id}"
|
||||
val download = com.droiddeck.launcher.stores.StoresState.download(key)
|
||||
val active = download?.isActive == true
|
||||
val check = GogMaintenance.checks[game.sidecar.id]
|
||||
LaunchedEffect(game.folder.path) { GogMaintenance.check(ctx, game) }
|
||||
LaunchedEffect(menu, active) {
|
||||
if (menu) {
|
||||
recoverablePatch = false
|
||||
val result = withContext(Dispatchers.IO) { runCatching {
|
||||
GogFiles.read(GogFiles.journal(game.folder))?.let {
|
||||
it.optString("operation") == GogOperation.PATCH.name && it.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain")
|
||||
} == true
|
||||
} }
|
||||
result.onSuccess { recoverablePatch = it }.onFailure { error = it.message }
|
||||
}
|
||||
}
|
||||
fun prepare(operation: GogOperation, patch: GogOfflineDownload? = null) {
|
||||
menu = false; patches = null; busy = true; error = null
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { GogMaintenance.prepare(ctx, game, operation, patch) } }
|
||||
.onSuccess { proposal = it }.onFailure { error = it.message }
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
if (active) {
|
||||
ActionChip(downloadLabel(download!!), ok = false)
|
||||
if (download.interruptible) {
|
||||
SecondaryButton(stringResource(if (download.state == DownloadState.PAUSED) R.string.stores_dl_resume else R.string.stores_dl_pause)) {
|
||||
if (download.state == DownloadState.PAUSED) DownloadQueue.resume(ctx, key) else DownloadQueue.pause(key)
|
||||
}
|
||||
} else Text(stringResource(R.string.gog_patch_in_session), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
} else if (!game.sidecar.isInstalled || GogFiles.journal(game.folder).exists()) {
|
||||
SecondaryButton(stringResource(R.string.gog_resume), modifier = Modifier.testTag("gog-resume")) {
|
||||
busy = true
|
||||
scope.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
GogMaintenance.resume(ctx, game)
|
||||
}
|
||||
}.onSuccess { proposal = it }.onFailure { error = it.message }
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
} else if (check?.state == GogMaintenance.State.AVAILABLE) {
|
||||
SecondaryButton(stringResource(R.string.gog_update, check.version.ifBlank { game.sidecar.title }), enabled = !busy, modifier = Modifier.testTag("gog-update")) { prepare(GogOperation.UPDATE) }
|
||||
}
|
||||
androidx.compose.foundation.layout.Box {
|
||||
SecondaryButton(stringResource(if (busy) R.string.common_checking else R.string.gog_maintenance), enabled = !busy && !active, modifier = Modifier.testTag("gog-maintenance")) { menu = !menu }
|
||||
AnchoredMenu(menu, { menu = false }, title = stringResource(R.string.gog_maintenance), compact = true) { first ->
|
||||
MenuItem(stringResource(R.string.common_update), checked = false) { prepare(GogOperation.UPDATE) }
|
||||
MenuItem(stringResource(R.string.gog_check), checked = false, focusRequester = first) { menu = false; GogMaintenance.check(ctx, game, true) }
|
||||
MenuItem(stringResource(R.string.gog_repair), checked = false, modifier = Modifier.testTag("gog-repair")) { prepare(GogOperation.REPAIR) }
|
||||
MenuItem(stringResource(R.string.gog_patches), checked = false, modifier = Modifier.testTag("gog-patches")) {
|
||||
menu = false; busy = true
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { GogMaintenance.offlinePatches(ctx, game) } }
|
||||
.onSuccess { patches = it }.onFailure { error = it.message }
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
MenuItem(stringResource(R.string.gog_refresh), checked = false) { prepare(GogOperation.REFRESH) }
|
||||
if (recoverablePatch) MenuItem(stringResource(R.string.gog_recover), checked = false, modifier = Modifier.testTag("gog-recover")) {
|
||||
menu = false; busy = true
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { GogMaintenance.recoverPatch(ctx, game) } }.onFailure { error = it.message }
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (check?.state == GogMaintenance.State.FAILED || check?.state == GogMaintenance.State.UNKNOWN) {
|
||||
if (check.reason.isNotBlank()) Text(check.reason, fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
patches?.let { list ->
|
||||
val shown = rememberShown { patches = null }
|
||||
val close = { shown.targetState = false }
|
||||
AppDialog(shown, close, "gogPatches", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(stringResource(R.string.gog_patches), close)
|
||||
Text(game.sidecar.title, fontSize = 12.sp, lineHeight = 16.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(stringResource(R.string.gog_patch_requirements), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
|
||||
if (list.isEmpty()) Text(stringResource(R.string.gog_no_patches), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
list.forEach { patch ->
|
||||
ListRow(onClick = { close(); prepare(GogOperation.PATCH, patch) }) {
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(patch.name, fontSize = 13.sp, lineHeight = 18.sp, fontWeight = FontWeight.Medium, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Text(listOf(StoreLanguage.displayName(patch.language).ifBlank { patch.language }, patch.version, formatBytes(patch.size)).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
fontSize = 11.sp, lineHeight = 15.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
Text(stringResource(R.string.gog_select_patch), fontSize = 12.sp, color = LocalPalette.current.signal)
|
||||
}
|
||||
}
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.gog_refresh)) { prepare(GogOperation.REFRESH) }
|
||||
}
|
||||
}
|
||||
proposal?.let { selected ->
|
||||
val shown = rememberShown { proposal = null }
|
||||
val close = { shown.targetState = false }
|
||||
val action = when (selected.operation) {
|
||||
GogOperation.UPDATE -> R.string.common_update
|
||||
GogOperation.REPAIR -> R.string.gog_repair_action
|
||||
GogOperation.PATCH -> R.string.gog_open_patch
|
||||
GogOperation.REFRESH -> R.string.gog_refresh_action
|
||||
}
|
||||
AppDialog(shown, close, "gogMaintenance", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(stringResource(action), close)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(listOf(game.sidecar.title, selected.before.version).filter { it.isNotBlank() }.joinToString(" · "), fontSize = 12.sp, lineHeight = 16.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (selected.operation != GogOperation.REPAIR) Text(selected.patch?.name ?: selected.target.version.ifBlank { selected.target.build }, fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface.copy(alpha = 0.65f)).padding(12.dp)) {
|
||||
GogMetric(stringResource(R.string.gog_download_label), formatBytes(selected.downloadBytes), Modifier.weight(1f))
|
||||
GogMetric(stringResource(if (selected.operation == GogOperation.PATCH || selected.operation == GogOperation.REFRESH) R.string.gog_space_estimate_label else R.string.gog_space_label),
|
||||
formatBytes(selected.diskBytes), Modifier.weight(1f))
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Text(stringResource(R.string.gog_managed_files), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
|
||||
if (selected.fullFiles) Text(stringResource(R.string.gog_full_files), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
|
||||
if (selected.operation == GogOperation.PATCH) Text(stringResource(R.string.gog_patch_installer_note), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
PrimaryButton(stringResource(action), enabled = !busy, modifier = Modifier.testTag("gog-apply")) {
|
||||
busy = true
|
||||
close()
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { GogMaintenance.enqueue(ctx, game, selected) } }.onFailure { error = it.message }
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.common_cancel), onClick = close)
|
||||
}
|
||||
}
|
||||
}
|
||||
error?.let { Text(it, fontSize = 12.sp, color = colors.error) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GogMetric(label: String, value: String, modifier: Modifier) {
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(label, fontSize = 11.sp, lineHeight = 15.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(value, fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,7 @@ import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollection
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollections
|
||||
import com.droiddeck.launcher.stores.itch.ItchUpdates
|
||||
import com.droiddeck.launcher.stores.gog.GogMaintenance
|
||||
import com.droiddeck.launcher.stores.retainOrder
|
||||
import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter
|
||||
import com.droiddeck.launcher.stores.sortGames
|
||||
@@ -586,13 +587,16 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) {
|
||||
download != null -> Text("${download.percent}%", fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
e.item != null && StoresState.isUnfinished(e.item) -> Text(stringResource(R.string.stores_resume), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
if (e.installed && e.storeKey?.let { it in ItchUpdates.available } == true) Text(stringResource(R.string.common_update), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
if (e.installed && libraryUpdateAvailable(e)) Text(stringResource(R.string.common_update), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
if (size != null && size > 0) Text(formatBytes(size), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
|
||||
if (!e.installed) Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.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) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -613,6 +617,7 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch
|
||||
val size = if (e.installed && folder != null) diskSize(inst, folder) else e.item?.let { StoreSizes.size(it) }?.takeIf { it > 0 }
|
||||
val status = when {
|
||||
download != null -> downloadLabel(download)
|
||||
e.installed && libraryUpdateAvailable(e) -> stringResource(R.string.common_update)
|
||||
!e.installed -> stringResource(R.string.stores_section_not_installed)
|
||||
e.game != null -> playedSpan(e.game.lastPlayed)?.replaceFirstChar { it.uppercase() } ?: stringResource(R.string.games_never_played)
|
||||
else -> stringResource(R.string.stores_installed_chip)
|
||||
|
||||
@@ -360,8 +360,10 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
when (d.state) {
|
||||
DownloadState.RUNNING, DownloadState.QUEUED -> {
|
||||
RoundAction(Icons.Filled.Pause, stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(d.key) }
|
||||
CancelAction { DownloadQueue.cancel(ctx, d.key) }
|
||||
if (d.interruptible) {
|
||||
RoundAction(Icons.Filled.Pause, stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(d.key) }
|
||||
CancelAction { DownloadQueue.cancel(ctx, d.key) }
|
||||
}
|
||||
}
|
||||
DownloadState.PAUSED -> {
|
||||
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.resume(ctx, d.key) }
|
||||
|
||||
@@ -1380,6 +1380,9 @@ private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droi
|
||||
val pal = LocalPalette.current
|
||||
val small = 10.sp
|
||||
when {
|
||||
item.store == Store.GOG && download != null -> Text("${download.percent}%", fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
item.store == Store.GOG && installed && com.droiddeck.launcher.stores.gog.GogMaintenance.checks[item.id]?.state == com.droiddeck.launcher.stores.gog.GogMaintenance.State.AVAILABLE ->
|
||||
Text(stringResource(R.string.common_update), fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
installed -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
val ctx = LocalContext.current
|
||||
val game = StoresState.installedGame(item.store, item.id)
|
||||
|
||||
Reference in new issue
Block a user