itch.io: version picker and installing free games (#1503)

* itch.io: temporary Test itch.io button that logs what the API answers (not for merge)

* itch.io: show Test itch.io only while Debugging tools is on

* itch.io: version picker and installing free games

* itch.io: build the platform names outside joinToString so the composable call compiles

* itch.io: ask for the version before resuming an unfinished install

* itch.io: keep the chosen upload, save free games in the queue, don't auto-install a closed picker

* itch.io: install straight away when exactly one build is installable

* itch.io: show the picker again unless the game has exactly one build

* itch.io: ignore a second build tap while the picker is closing

* itch.io: empty a partial install before extracting so builds never mix

* stores: deleteTree removes a symlink without following it

* stores: skip symlinked folders in the uninstall walk, and only empty a partial install that is this game's own
This commit is contained in:
FX1922 authored and GitHub committed 2026-10-25 12:37:04 -04:00
1 parent 7d99a24ad5
commit 411fda343a
46 files changed
+541 -11

No files matched your search

@@ -70,7 +70,7 @@ object StoreInstalls {
fun uninstall(context: Context, game: InstalledStoreGame, progress: (Float) -> Unit = {}, removed: () -> Unit = {}) {
val app = context.applicationContext
val appId = SessionPrefs.addedGameStoredAppId(app, game.folder.path)
val files = game.folder.walkBottomUp().toList()
val files = game.folder.walkBottomUp().onEnter { !Files.isSymbolicLink(it.toPath()) }.toList()
val step = (files.size / 100).coerceAtLeast(1)
files.forEachIndexed { i, f ->
f.delete()
@@ -98,6 +98,10 @@ object StoreInstalls {
}
fun deleteTree(dir: File) {
if (Files.isSymbolicLink(dir.toPath())) {
dir.delete()
return
}
dir.listFiles()?.forEach { if (it.isDirectory) deleteTree(it) else it.delete() }
dir.delete()
}
@@ -212,9 +212,11 @@ object StoresState {
}
var pendingInstall by mutableStateOf<CatalogItem?>(null)
var itchPicking by mutableStateOf<CatalogItem?>(null)
fun requestInstall(context: Context, item: CatalogItem) {
askForNotifications(context)
if (item.store == Store.ITCH && item.extra["uploadId"].isNullOrEmpty()) { itchPicking = item; return }
if (isUnfinished(item)) { install(context, item); return }
val targets = StoreInstallRoot.targets(context)
if (targets.size > 1 || StoreLanguage.selectable(item.store)) pendingInstall = item
@@ -79,7 +79,7 @@ object SavedQueue {
put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: "")
i.logoUrl?.let { put("logo", it) }
put("tags", i.tags); put("developer", i.developer); put("description", i.description)
put("size", i.sizeBytes); put("owned", i.owned); put("subscription", i.subscription)
put("size", i.sizeBytes); put("owned", i.owned); put("subscription", i.subscription); put("free", i.isFree)
put("extra", JSONObject(i.extra))
}
@@ -90,7 +90,7 @@ object SavedQueue {
id = o.getString("id"), title = o.getString("title"),
imageUrl = o.optString("image").ifEmpty { null }, tallImageUrl = o.optString("tall").ifEmpty { null },
tags = o.optString("tags"), developer = o.optString("developer"), description = o.optString("description"),
owned = o.optBoolean("owned", true), subscription = o.optBoolean("subscription"), sizeBytes = o.optLong("size"),
owned = o.optBoolean("owned", true), subscription = o.optBoolean("subscription"), isFree = o.optBoolean("free"), sizeBytes = o.optLong("size"),
extra = extra?.keys()?.asSequence()?.associateWith { extra.getString(it) } ?: emptyMap(),
logoUrl = o.optString("logo").ifEmpty { null },
)
@@ -20,7 +20,7 @@ internal object ItchApi {
fun ownedKeys(key: String, page: Int): JSONObject? = get("/profile/owned-keys?page=$page&per_page=500", key)
fun uploads(key: String, gameId: String, downloadKeyId: String): JSONArray? =
get("/games/$gameId/uploads?download_key_id=$downloadKeyId", key)?.optJSONArray("uploads")
get("/games/$gameId/uploads" + keyQuery(downloadKeyId), key)?.optJSONArray("uploads")
fun search(key: String, query: String, page: Int): JSONArray? {
val q = java.net.URLEncoder.encode(query, "UTF-8")
@@ -28,7 +28,9 @@ internal object ItchApi {
}
fun downloadUrl(uploadId: String, downloadKeyId: String): String =
"$BASE/uploads/$uploadId/download?download_key_id=$downloadKeyId"
"$BASE/uploads/$uploadId/download" + keyQuery(downloadKeyId)
private fun keyQuery(downloadKeyId: String): String = if (downloadKeyId.isBlank()) "" else "?download_key_id=$downloadKeyId"
fun pageUrl(slug: String): String = "$WEB/$slug"
}
@@ -55,7 +55,7 @@ object ItchBackend : StoreBackend {
override fun install(context: Context, item: CatalogItem, root: File) {
val app = context.applicationContext
if (item.extra["downloadKeyId"].isNullOrEmpty()) {
if (item.extra["downloadKeyId"].isNullOrEmpty() && !item.isFree) {
StoresState.logLine("itch.io: \"${item.title}\" is not in the library")
return
}
@@ -0,0 +1,44 @@
package com.droiddeck.launcher.stores.itch
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.StoreNet
import org.json.JSONArray
internal class ItchBuild(
val uploadId: String,
val filename: String,
val size: Long,
val updatedAt: String,
val platforms: Set<String>,
val demo: Boolean,
) {
val installable: Boolean get() = "windows" in platforms
}
internal object ItchGame {
private val PATH_AFTER = Regex("""name="itch:path"[^>]*content="games/(\d+)"""")
private val PATH_BEFORE = Regex("""content="games/(\d+)"[^>]*name="itch:path"""")
fun idFromPage(html: String): String? =
PATH_AFTER.find(html)?.groupValues?.get(1) ?: PATH_BEFORE.find(html)?.groupValues?.get(1)
fun resolveId(item: CatalogItem): String? {
item.extra["gameId"]?.takeIf { it.isNotBlank() }?.let { return it }
if (item.storeUrl.isBlank()) return null
val html = StoreNet.get(item.storeUrl) ?: return null
return idFromPage(html)
}
fun builds(uploads: JSONArray?): List<ItchBuild> {
if (uploads == null) return emptyList()
return (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) }
.filter { it.optString("storage") != "external" }
.map {
ItchBuild(
it.optString("id"), ItchUploads.filename(it), ItchUploads.size(it),
it.optString("updated_at", it.optString("updatedAt")), ItchUploads.platforms(it), it.optBoolean("demo"),
)
}
.sortedWith(compareByDescending<ItchBuild> { it.installable }.thenByDescending { it.updatedAt })
}
}
@@ -38,11 +38,14 @@ internal class ItchInstaller(
val key = ItchAuth.key(app)
if (key.isBlank()) throw IllegalStateException(app.getString(R.string.stores_sync_sign_in))
val downloadKeyId = item.extra["downloadKeyId"].orEmpty()
if (downloadKeyId.isBlank()) throw IllegalStateException(app.getString(R.string.stores_itch_not_owned))
val gameId = item.extra["gameId"].orEmpty().ifBlank { item.id.substringAfterLast('/') }
if (downloadKeyId.isBlank() && !item.isFree) throw IllegalStateException(app.getString(R.string.stores_itch_not_owned))
val gameId = ItchGame.resolveId(item) ?: throw IllegalStateException(app.getString(R.string.stores_itch_no_game))
val resuming = StoreGameSidecar.read(folder)?.let { it.state == StoreGameSidecar.STATE_INSTALLING && it.id == item.id } == true
StoreInstalls.begin(folder, Store.ITCH, item.id, item.title, item.imageUrl, item.imageUrl)
handle.stage(DownloadStage.MANIFEST)
val upload = ItchUploads.windows(ItchApi.uploads(key, gameId, downloadKeyId))
val uploads = ItchApi.uploads(key, gameId, downloadKeyId)
val chosen = item.extra["uploadId"].orEmpty()
val upload = (if (chosen.isBlank()) ItchUploads.windows(uploads) else ItchUploads.byId(uploads, chosen))
?: throw IllegalStateException(app.getString(R.string.stores_itch_no_upload))
val uploadId = upload.optString("id")
val filename = ItchUploads.filename(upload)
@@ -55,7 +58,7 @@ internal class ItchInstaller(
download(key, downloadKeyId, uploadId, upload.optString("updated_at", upload.optString("updatedAt")), archive, size, handle)
if (cancelled.get()) return null
handle.stage(DownloadStage.INSTALL)
install(archive, filename, handle)
install(archive, filename, handle, resuming)
} catch (t: Throwable) {
if (!cancelled.get()) StoreInstalls.discard(app, folder, listOf(scratch))
throw t
@@ -147,8 +150,16 @@ internal class ItchInstaller(
}
}
private fun install(archive: File, filename: String, handle: DownloadQueue.JobHandle): String? {
private fun clearPartialInstall() {
folder.listFiles()?.forEach {
if (it.name == StoreGameSidecar.FILE_NAME) return@forEach
if (it.isDirectory) StoreInstalls.deleteTree(it) else it.delete()
}
}
private fun install(archive: File, filename: String, handle: DownloadQueue.JobHandle, resuming: Boolean): String? {
folder.mkdirs()
if (resuming) clearPartialInstall()
when (val kind = sniff(archive, filename)) {
"zip" -> unzip(archive, handle)
"7z" -> sevenZip(archive, handle)
@@ -30,6 +30,28 @@ internal object ItchUploads {
return names.none { it in PLATFORM_TRAITS }
}
fun platforms(upload: JSONObject): Set<String> {
val found = LinkedHashSet<String>()
upload.optJSONObject("platforms")?.let { flags ->
for (name in listOf("windows", "linux", "osx", "android")) if (flags.optBoolean(name)) found.add(name)
}
upload.optJSONArray("traits")?.let { traits ->
for (i in 0 until traits.length()) when (traits.optString(i)) {
"p_windows" -> found.add("windows")
"p_linux" -> found.add("linux")
"p_osx" -> found.add("osx")
"p_android" -> found.add("android")
}
}
if (upload.optString("type") == "html") found.add("web")
return if (found.isEmpty()) setOf("windows") else found
}
fun byId(uploads: JSONArray?, id: String): JSONObject? {
if (uploads == null || id.isBlank()) return null
return (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) }.firstOrNull { it.optString("id") == id }
}
fun size(upload: JSONObject): Long = upload.optLong("size", upload.optLong("size_bytes"))
fun filename(upload: JSONObject): String = upload.optString("filename").substringAfterLast('/')
@@ -561,6 +561,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
FlightsLayer(screenAt)
GamesDialogs(a, s.steamGames)
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
StepsLayer(screenAt)
appToChooseDisplay?.let { app ->
@@ -397,6 +397,10 @@ private fun GameActions(
}
if (!item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) }
}
item != null && item.store == Store.ITCH && item.isFree -> {
InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) }
}
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
}
@@ -0,0 +1,117 @@
package com.droiddeck.launcher.ui
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.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.key
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.itch.ItchApi
import com.droiddeck.launcher.stores.itch.ItchAuth
import com.droiddeck.launcher.stores.itch.ItchBuild
import com.droiddeck.launcher.stores.itch.ItchGame
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
private class BuildList(val gameId: String, val builds: List<ItchBuild>)
@Composable
internal fun ItchBuildPicker(item: CatalogItem, onDismiss: () -> Unit) {
val ctx = LocalContext.current
val app = ctx.applicationContext
val colors = MaterialTheme.colorScheme
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
var loaded by remember(item) { mutableStateOf<BuildList?>(null) }
var failed by remember(item) { mutableStateOf(false) }
val install: (BuildList, ItchBuild) -> Unit = install@{ list, build ->
if (!shown.targetState) return@install
val tagged = item.copy(
extra = item.extra + mapOf("gameId" to list.gameId, "uploadId" to build.uploadId),
sizeBytes = build.size.takeIf { it > 0 } ?: item.sizeBytes,
)
close()
StoresState.requestInstall(ctx, tagged)
}
LaunchedEffect(item) {
val result = withContext(Dispatchers.IO) {
val key = ItchAuth.key(app)
val id = if (key.isBlank()) null else ItchGame.resolveId(item)
val uploads = id?.let { ItchApi.uploads(key, it, item.extra["downloadKeyId"].orEmpty()) }
if (id == null || uploads == null) null else BuildList(id, ItchGame.builds(uploads))
}
if (result == null) { failed = true; return@LaunchedEffect }
loaded = result
if (shown.targetState) result.builds.singleOrNull()?.takeIf { it.installable }?.let { install(result, it) }
}
AppDialog(shown, close, "itchBuilds", wide = false, maxWidth = 460.dp) {
DialogTitleRow(stringResource(R.string.stores_itch_pick_title), close)
Text(item.title, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
val list = loaded
when {
failed -> Text(stringResource(R.string.stores_itch_pick_failed), fontSize = 13.sp, color = colors.onSurfaceVariant)
list == null -> LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 8.dp))
list.builds.isEmpty() -> Text(stringResource(R.string.stores_itch_pick_none), fontSize = 13.sp, color = colors.onSurfaceVariant)
else -> Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
for (build in list.builds) key(build.uploadId) { BuildRow(item, build) { install(list, build) } }
}
}
}
}
@Composable
private fun BuildRow(item: CatalogItem, build: ItchBuild, onInstall: () -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val linux = "linux" in build.platforms && !build.installable
val detail = listOfNotNull(
build.platforms.map { platformName(it) }.joinToString(", "),
build.size.takeIf { it > 0 }?.let { formatBytes(it) },
build.updatedAt.take(10).takeIf { it.isNotBlank() },
if (build.demo) stringResource(R.string.stores_itch_build_demo) else null,
).joinToString(" · ")
ListRow(enabled = !linux, onClick = { if (build.installable) onInstall() else openStoreUrl(ctx, item) }) {
Column(Modifier.weight(1f)) {
Text(build.filename.ifBlank { item.title }, fontSize = 13.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(detail, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
val label = when {
build.installable -> stringResource(R.string.stores_install)
linux -> stringResource(R.string.stores_itch_build_linux_soon)
else -> stringResource(R.string.stores_itch_build_open)
}
Text(label, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
}
@Composable
private fun platformName(platform: String): String = stringResource(
when (platform) {
"windows" -> R.string.stores_itch_build_windows
"linux" -> R.string.stores_itch_build_linux
"osx" -> R.string.stores_itch_build_macos
"android" -> R.string.stores_itch_build_android
else -> R.string.stores_itch_build_web
},
)