feat: Add the Game Jolt store (#1986)

This commit is contained in:
FX1922 authored and GitHub committed 2026-11-02 10:05:30 -05:00
1 parent 0050b5eb6b
commit 3583643a11
74 files changed
+3215 -275

No files matched your search

@@ -55,6 +55,7 @@ class App : Application() {
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gamejolt.GameJoltBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
com.droiddeck.launcher.sync.Syncthing.init(this)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
@@ -87,7 +87,7 @@ object CloudSaves {
val item = sidecar.extra["catalogItemId"].orEmpty()
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
}
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> ""
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> ""
} ?: return null
p.edit()
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
@@ -148,7 +148,7 @@ object CloudSaves {
val dir = when (store) {
Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> null
}
return dir to (if (dir == null) "unresolved" else "ok")
}
@@ -173,7 +173,7 @@ object CloudSaves {
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
}
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> null
}
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
@@ -12,11 +12,13 @@ internal object LoginFlows {
Store.GOG -> GogFlow(state, browserUserAgent)
Store.EPIC -> epicFlow()
Store.AMAZON -> amazonFlow()
Store.GAMEJOLT -> gameJoltFlow(browserUserAgent)
Store.ITCH, Store.XBOX, Store.BATTLENET -> null
}
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
@Volatile var amazonFlow: () -> StoreLoginActivity.Flow? = { null }
@Volatile var gameJoltFlow: (String) -> StoreLoginActivity.Flow? = { null }
private class GogFlow(private val state: String, override val userAgent: String) : StoreLoginActivity.Flow {
override val startUrl: String get() = GogAuth.authUrl(state)
@@ -5,9 +5,12 @@ enum class Store(val id: String, val label: String, val shortLabel: String) {
EPIC("epic", "Epic Games", "Epic"),
AMAZON("amazon", "Amazon Games", "Amazon"),
XBOX("xbox", "Xbox", "Xbox"),
ITCH("itch", "itch.io", "itch"),
ITCH("itch", "Itch.io", "Itch.io"),
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"),
BATTLENET("battlenet", "Battle.net", "Battle.net");
val folder: String get() = if (this == ITCH) "itch" else shortLabel
companion object {
fun byId(id: String?): Store? = entries.firstOrNull { it.id == id }
}
@@ -0,0 +1,231 @@
package com.droiddeck.launcher.stores
import android.content.Context
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.itch.ItchArchives
import org.apache.commons.compress.MemoryLimitException
import org.apache.commons.compress.archivers.sevenz.SevenZFile
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import org.apache.commons.compress.archivers.zip.ZipFile
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.file.Files
import java.util.concurrent.atomic.AtomicBoolean
internal class StoreArchiveUnpacker(
private val app: Context,
private val cancelled: AtomicBoolean,
private val label: String,
private val unsupported: Int,
private val extractFailed: Int,
private val logName: String,
) {
var work: File = File("")
fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) {
when (val kind = ItchArchives.kind(archive, filename)) {
"zip" -> unzip(archive, handle)
"7z" -> try {
sevenZip(archive, handle)
} catch (e: MemoryLimitException) {
handle.log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime")
unrar(archive, handle, kind)
}
"rar" -> unrar(archive, handle, kind)
"exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" }))
"tar" -> untar(archive, null, handle)
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
else -> copy(archive, File(work, filename.ifBlank { "game" }))
}
}
private fun target(name: String): File? {
val file = File(work, name.replace('\\', '/'))
val root = work.canonicalPath
val path = file.canonicalPath
return if (path == root || path.startsWith(root + File.separator)) file else null
}
private fun unrar(archive: File, handle: DownloadQueue.JobHandle, kind: String) {
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(unsupported, kind))
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
else listOf(work.absolutePath)
fun bsdtar(args: List<String>, onLine: (String) -> Unit) =
GuestCommand.run(app, listOf("/usr/bin/bsdtar") + args, logName = logName, extraBinds = binds, fastPath = true, cancelled = cancelled) { line ->
if (!line.startsWith("proot ")) onLine(line)
}
var entries = 0L
bsdtar(listOf("-tf", archive.absolutePath)) { entries++ }
var done = 0L
val tail = ArrayDeque<String>()
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line ->
if (line.startsWith("x ")) handle.stageProgress(++done, entries) else {
if (tail.size == 5) tail.removeFirst()
tail.addLast(line)
}
}
if (cancelled.get()) return
if (code != 0) {
handle.log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}")
throw IllegalStateException(app.getString(extractFailed, code))
}
}
private fun sevenZip(archive: File, handle: DownloadQueue.JobHandle) {
val total = archive.length()
var written = 0L
val buffer = ByteArray(64 * 1024)
val limitKb = (Runtime.getRuntime().maxMemory() / 4 / 1024).coerceIn(32L * 1024, Int.MAX_VALUE.toLong()).toInt()
Files.newByteChannel(archive.toPath()).use { channel ->
SevenZFile.builder().setSeekableByteChannel(channel).setMaxMemoryLimitKb(limitKb).get().use { seven ->
while (true) {
if (cancelled.get()) return
val entry = seven.nextEntry ?: break
val file = target(entry.name)
if (file == null) {
handle.log("$label: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
file.mkdirs()
continue
}
file.parentFile?.mkdirs()
FileOutputStream(file).use { out ->
while (true) {
if (cancelled.get()) return
val read = seven.read(buffer, 0, buffer.size)
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
}
}
}
}
}
}
private fun untar(archive: File, codec: String?, handle: DownloadQueue.JobHandle): Unit? {
val total = archive.length()
var written = 0L
var entries = 0
val buffer = ByteArray(64 * 1024)
val opened = runCatching {
FileInputStream(archive).use { raw ->
val stream = when (codec) {
"gz" -> GzipCompressorInputStream(BufferedInputStream(raw))
"bz2" -> BZip2CompressorInputStream(BufferedInputStream(raw))
"xz" -> XZCompressorInputStream(BufferedInputStream(raw))
else -> BufferedInputStream(raw)
}
stream.use { input ->
TarArchiveInputStream(input).use { tar ->
while (true) {
if (cancelled.get()) return null
val entry = tar.nextEntry ?: break
entries++
val file = target(entry.name)
if (file == null) {
handle.log("$label: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
file.mkdirs()
continue
}
file.parentFile?.mkdirs()
FileOutputStream(file).use { out ->
while (true) {
if (cancelled.get()) return null
val read = tar.read(buffer, 0, buffer.size)
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
}
}
}
}
}
}
true
}
if (opened.isSuccess && entries > 0) return Unit
if (opened.isFailure && codec == null) throw opened.exceptionOrNull() ?: IllegalStateException("tar")
return null
}
private fun single(archive: File, codec: String, handle: DownloadQueue.JobHandle) {
val name = archive.name.substringBeforeLast('.')
val file = target(name.ifBlank { "game" }) ?: throw IllegalStateException("archive")
file.parentFile?.mkdirs()
val total = archive.length()
var written = 0L
val buffer = ByteArray(64 * 1024)
FileInputStream(archive).use { raw ->
val stream = when (codec) {
"bz2" -> BZip2CompressorInputStream(BufferedInputStream(raw))
"xz" -> XZCompressorInputStream(BufferedInputStream(raw))
else -> GzipCompressorInputStream(BufferedInputStream(raw))
}
stream.use { input ->
FileOutputStream(file).use { out ->
while (true) {
if (cancelled.get()) return
val read = input.read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
}
}
}
}
}
private fun copy(source: File, target: File) {
target.parentFile?.mkdirs()
FileInputStream(source).use { input -> FileOutputStream(target).use { out -> input.copyTo(out, 128 * 1024) } }
}
private fun unzip(archive: File, handle: DownloadQueue.JobHandle) {
val total = archive.length()
var written = 0L
val buffer = ByteArray(64 * 1024)
ZipFile.builder().setFile(archive).get().use { zip ->
for (entry in zip.entries) {
if (cancelled.get()) return
val target = target(entry.name)
if (target == null) {
handle.log("$label: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
target.mkdirs()
continue
}
target.parentFile?.mkdirs()
zip.getInputStream(entry).use { input ->
FileOutputStream(target).use { out ->
while (true) {
if (cancelled.get()) return
val read = input.read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
}
}
}
}
}
}
}
@@ -218,7 +218,7 @@ object StoreInstallRoot {
fun isRemovable(context: Context, folder: File): Boolean = !folder.absolutePath.startsWith(internalRoot(context).absolutePath + "/")
fun storeDir(root: File, store: Store): File = File(root, store.shortLabel)
fun storeDir(root: File, store: Store): File = File(root, store.folder)
fun gameFolders(context: Context): List<File> = roots(context).flatMap { root ->
Store.entries.flatMap { store ->
@@ -273,6 +273,10 @@ class StoreLoginActivity : ComponentActivity() {
if (url != null && view != null && flow?.isRedirect(url) == true && flow?.readsPage != true) complete(view, url)
}
override fun doUpdateVisitedHistory(view: WebView?, url: String?, isReload: Boolean) {
if (!isPopup && store == Store.GAMEJOLT && url != null && view != null && flow?.isRedirect(url) == true && flow?.readsPage != true) complete(view, url)
}
override fun onPageFinished(view: WebView?, url: String?) {
if (url != null && view != null && flow?.readsPage == true && flow?.isRedirect(url) == true) complete(view, url)
}
@@ -54,7 +54,7 @@ object StoreSizes {
when (item.store) {
Store.EPIC -> EpicPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
Store.ITCH -> {}
Store.ITCH, Store.GAMEJOLT -> {}
Store.GOG, Store.XBOX, Store.BATTLENET -> {}
}
}
@@ -113,5 +113,6 @@ object StoreSizes {
}
Store.GOG, Store.XBOX, Store.BATTLENET -> 0L
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item)
} }
}
@@ -131,7 +131,11 @@ object StoresState {
fun detailItem(store: Store, id: String): CatalogItem? = detailCatalogItem(
store, id, library[store].orEmpty(),
found[store].orEmpty() + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchBrowseState.items + com.droiddeck.launcher.stores.itch.ItchCollections.items() else emptyList(),
found[store].orEmpty() + when (store) {
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchBrowseState.items + com.droiddeck.launcher.stores.itch.ItchCollections.items()
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBrowseState.items + com.droiddeck.launcher.stores.gamejolt.GameJoltCollections.items()
else -> emptyList()
},
shelves[store],
)
@@ -191,6 +195,10 @@ object StoresState {
backend?.signOut(app)
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) }
else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store)
if (store == Store.GAMEJOLT) {
com.droiddeck.launcher.stores.gamejolt.GameJoltCollections.clear()
com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates.clear(app)
}
if (store == Store.ITCH) {
com.droiddeck.launcher.stores.itch.ItchCollections.clear()
com.droiddeck.launcher.stores.itch.ItchUpdates.clear(app)
@@ -218,10 +226,12 @@ object StoresState {
var pendingInstall by mutableStateOf<CatalogItem?>(null)
var itchPicking by mutableStateOf<CatalogItem?>(null)
var gameJoltPicking 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 (item.store == Store.GAMEJOLT && item.extra["buildId"].isNullOrEmpty()) { gameJoltPicking = item; return }
if (isUnfinished(item)) { install(context, item); return }
val targets = StoreInstallRoot.targets(context)
val preferred = StoreInstallRoot.defaultTarget(context)
@@ -285,6 +295,7 @@ object StoresState {
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
uninstalling.remove(key)
if (game.sidecar.store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchUpdates.applied(app, key)
if (game.sidecar.store == Store.GAMEJOLT) com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates.applied(app, key)
}
})
main.post(onDone)
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.stores.gamejolt
import com.droiddeck.launcher.stores.StoreNet
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
internal class GameJoltAnswer(val code: Int, val json: JSONObject?) {
val ok: Boolean get() = code in 200..299
val payload: JSONObject? get() = json?.optJSONObject("payload")
val user: JSONObject? get() = json?.optJSONObject("user")
}
internal object GameJoltApi {
const val SITE = "https://gamejolt.com"
const val LOGIN = "$SITE/login"
private const val BASE = "$SITE/site-api"
private const val MAX_BYTES = 6_000_000
fun get(path: String, cookies: String = ""): GameJoltAnswer = send("GET", path, cookies, null)
fun post(path: String, cookies: String = "", body: String = ""): GameJoltAnswer = send("POST", path, cookies, body)
fun overview(gameId: String, cookies: String): GameJoltAnswer = get("/web/discover/games/overview/$gameId", cookies)
fun search(query: String, page: Int, cookies: String): GameJoltAnswer =
get("/web/search/games?q=${URLEncoder.encode(query, "UTF-8")}&page=$page", cookies)
fun browse(queryString: String, cookies: String): GameJoltAnswer = get("/web/discover/games?$queryString", cookies)
fun pageUrl(slug: String, id: String): String = "$SITE/games/$slug/$id"
private fun readBounded(input: java.io.InputStream): String {
val out = java.io.ByteArrayOutputStream()
val buffer = ByteArray(16 * 1024)
while (out.size() < MAX_BYTES) {
val read = input.read(buffer, 0, minOf(buffer.size, MAX_BYTES - out.size()))
if (read < 0) break
out.write(buffer, 0, read)
}
return out.toString(Charsets.UTF_8.name())
}
private fun send(method: String, path: String, cookies: String, body: String?): GameJoltAnswer {
var conn: HttpURLConnection? = null
return try {
conn = (URL(BASE + path).openConnection() as HttpURLConnection).apply {
connectTimeout = 25_000
readTimeout = 25_000
requestMethod = method
setRequestProperty("User-Agent", StoreNet.BROWSER_UA)
setRequestProperty("Accept", "application/json")
if (cookies.isNotBlank()) setRequestProperty("Cookie", cookies)
if (body != null) {
doOutput = true
setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
}
}
if (body != null) conn.outputStream.use { it.write(body.toByteArray()) }
val code = conn.responseCode
val stream = if (code in 200..399) conn.inputStream else conn.errorStream
val text = stream?.use { readBounded(it) }.orEmpty()
GameJoltAnswer(code, runCatching { JSONObject(text) }.getOrNull())
} catch (e: Exception) {
GameJoltAnswer(0, null)
} finally {
runCatching { conn?.disconnect() }
}
}
}
@@ -0,0 +1,24 @@
package com.droiddeck.launcher.stores.gamejolt
import android.content.Context
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import org.json.JSONObject
internal object GameJoltAuth {
fun cookies(context: Context): String = StoreAccounts.read(context.applicationContext, Store.GAMEJOLT)?.optString("access_token").orEmpty()
fun save(context: Context, cookies: String, user: JSONObject) {
val name = user.optString("display_name").ifBlank { user.optString("username") }
StoreAccounts.write(
context.applicationContext, Store.GAMEJOLT,
JSONObject().put("access_token", cookies).put("user_id", user.optLong("id").toString()).put("username", user.optString("username")).put("display_name", name),
)
}
fun username(context: Context): String = StoreAccounts.read(context.applicationContext, Store.GAMEJOLT)?.optString("username").orEmpty()
fun userId(context: Context): String = StoreAccounts.read(context.applicationContext, Store.GAMEJOLT)?.optString("user_id").orEmpty()
fun clear(context: Context) = StoreAccounts.clear(context.applicationContext, Store.GAMEJOLT)
}
@@ -0,0 +1,86 @@
package com.droiddeck.launcher.stores.gamejolt
import android.content.Context
import android.content.Intent
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.LoginFlows
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreBackend
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.StoreShelves
import com.droiddeck.launcher.stores.StoreSizes
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import java.io.File
object GameJoltBackend : StoreBackend {
override val store: Store = Store.GAMEJOLT
init {
LoginFlows.gameJoltFlow = { agent -> GameJoltLogin(agent) }
}
override fun signIn(context: Context) {
context.startActivity(
Intent(context, StoreLoginActivity::class.java)
.putExtra(StoreLoginActivity.EXTRA_STORE, store.id)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
}
override fun signOut(context: Context) {
val app = context.applicationContext
GameJoltPrefs.get(app).edit().clear().apply()
GameJoltAuth.clear(app)
GameJoltLibrary.reset()
StoresState.post {
StoresState.library.remove(store)
StoresState.shelves.remove(store)
StoresState.found.remove(store)
StoresState.problems.remove(store)
StoresState.status.remove(store)
}
}
override fun syncLibrary(context: Context, force: Boolean) {
val app = context.applicationContext
if (force) GameJoltLibrary.reset()
Thread({ GameJoltLibrary.sync(app, force) }, "gamejolt-sync").start()
}
override fun loadShelves(context: Context, force: Boolean) {
StoresState.post { StoresState.shelves[store] = StoreShelves() }
}
override fun search(context: Context, query: String): List<CatalogItem> {
val cookies = GameJoltAuth.cookies(context)
val items = ArrayList<CatalogItem>()
for (page in 1..2) {
val answer = GameJoltApi.search(query, page, cookies)
val found = if (answer.ok) GameJoltCatalog.items(answer.payload?.optJSONArray("games")) else emptyList()
if (found.isEmpty()) break
items.addAll(found)
}
StoresState.logLine("Game Jolt search: \"$query\" returned ${items.size} games")
return items.distinctBy { it.id }
}
override fun install(context: Context, item: CatalogItem, root: File) {
val app = context.applicationContext
if (!item.isFree && !item.owned) {
StoresState.logLine("Game Jolt: \"${item.title}\" is a paid game, opening its page instead")
return
}
val folder = StoreInstallRoot.folderFor(app, Store.GAMEJOLT, item.id, item.title, root)
val entry = DownloadEntry(
Store.GAMEJOLT, item.id, item.title, cover = item.imageUrl, bytesTotal = StoreSizes.size(item),
location = StoreInstallRoot.labelFor(app, folder),
)
DownloadQueue.enqueue(app, entry) { GameJoltInstaller(app, item, folder) }
}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
}
@@ -0,0 +1,163 @@
package com.droiddeck.launcher.stores.gamejolt
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoresState
import java.net.URLEncoder
internal data class GameJoltQuery(
val section: String = GameJoltBrowse.SECTION_FEATURED,
val price: String = GameJoltBrowse.PRICE_ANY,
val os: Set<String> = emptySet(),
val browser: Set<String> = emptySet(),
val maturity: Set<String> = emptySet(),
val status: Set<String> = emptySet(),
val partners: Boolean = false,
val tags: List<String> = emptyList(),
)
internal object GameJoltBrowse {
const val SECTION_FEATURED = "featured"
const val SECTION_HOT = "hot"
const val SECTION_BEST = "best"
const val SECTION_NEW = "new"
val sections = listOf(SECTION_FEATURED, SECTION_HOT, SECTION_BEST, SECTION_NEW)
const val PRICE_ANY = "any"
const val PRICE_FREE = "free"
const val PRICE_SALE = "sale"
const val PRICE_PAID = "paid"
const val PRICE_UNDER_5 = "5-less"
const val PRICE_UNDER_15 = "15-less"
const val PRICE_UNDER_30 = "30-less"
val prices = listOf(PRICE_ANY, PRICE_FREE, PRICE_SALE, PRICE_PAID, PRICE_UNDER_5, PRICE_UNDER_15, PRICE_UNDER_30)
val systems = listOf("windows", "mac", "linux", "other")
val browsers = listOf("html", "flash", "unity")
val maturities = listOf("everyone", "teen", "adult")
val statuses = listOf("complete", "wip")
fun tagSlug(tag: String): String = tag.trim().lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-')
fun queryString(query: GameJoltQuery, page: Int): String {
val parts = ArrayList<String>()
parts.add("section=${query.section.takeIf { it in sections } ?: SECTION_FEATURED}")
query.tags.forEach { parts.add("tag=" + enc(tagSlug(it))) }
if (query.price != PRICE_ANY && query.price in prices) parts.add("f_price=${query.price}")
systems.filter { it in query.os }.forEach { parts.add("f_os%5B%5D=$it") }
browsers.filter { it in query.browser }.forEach { parts.add("f_browser%5B%5D=$it") }
maturities.filter { it in query.maturity }.forEach { parts.add("f_maturity%5B%5D=$it") }
statuses.filter { it in query.status }.forEach { parts.add("f_status%5B%5D=$it") }
if (query.partners) parts.add("f_partners%5B%5D=partners")
if (page > 1) parts.add("page=$page")
return parts.joinToString("&")
}
private fun enc(value: String): String = URLEncoder.encode(value, "UTF-8")
class Page(val items: List<CatalogItem>, val code: Int, val rawIds: List<String>)
fun effective(query: GameJoltQuery, showMature: Boolean): GameJoltQuery {
val playable = query.copy(status = query.status.filterTo(HashSet()) { it in statuses }.ifEmpty { statuses.toSet() })
if (showMature) return playable
val allowed = playable.maturity - "adult"
return playable.copy(maturity = allowed.ifEmpty { setOf("everyone", "teen") })
}
fun page(context: Context, query: GameJoltQuery, page: Int, showMature: Boolean): Page {
val cookies = GameJoltAuth.cookies(context)
val asked = effective(query, showMature)
val answer = fetch(queryString(asked, page), cookies)
val all = if (answer.ok) GameJoltCatalog.items(answer.payload?.optJSONArray("games")) else emptyList()
return Page(all, answer.code, all.map { it.id })
}
private fun fetch(qs: String, cookies: String): GameJoltAnswer {
val answer = GameJoltApi.browse(qs, cookies)
val games = if (answer.ok) answer.payload?.optJSONArray("games") else null
StoresState.logLine("Game Jolt browse: ?$qs answered ${answer.code} with ${games?.length() ?: 0} games")
return answer
}
}
internal object GameJoltBrowseState {
var query by mutableStateOf(GameJoltQuery())
private set
var items by mutableStateOf<List<CatalogItem>>(emptyList())
private set
var loading by mutableStateOf(false)
private set
var ended by mutableStateOf(false)
private set
var failed by mutableStateOf(false)
private set
private var next = 1
private var generation = 0
private var loadedMature: Boolean? = null
private val seenRaw = HashSet<String>()
fun sync(context: Context, showMature: Boolean) {
if (!showMature && "adult" in query.maturity) {
reset()
query = query.copy(maturity = query.maturity - "adult")
more(context)
return
}
val before = loadedMature ?: return
if (before != showMature) more(context)
}
private fun reset() {
generation++
items = emptyList()
ended = false
failed = false
loading = false
next = 1
seenRaw.clear()
}
fun choose(context: Context, wanted: GameJoltQuery) {
if (wanted == query) return
reset()
query = wanted
more(context)
}
fun more(context: Context, retry: Boolean = false) {
val app = context.applicationContext
val mature = SessionPrefs.storesShowMature(app)
if (loadedMature != null && loadedMature != mature) reset()
if (loading || ended || (failed && !retry)) return
loading = true
failed = false
val mine = generation
val asked = query
val page = next
loadedMature = mature
Thread({
val answer = runCatching { GameJoltBrowse.page(app, asked, page, mature) }.getOrNull()
StoresState.post {
if (mine != generation) return@post
loading = false
if (answer == null || answer.code !in 200..299) {
failed = true
return@post
}
if (answer.rawIds.filter { seenRaw.add(it) }.isEmpty()) {
ended = true
return@post
}
next = page + 1
val known = items.mapTo(HashSet()) { it.id }
val fresh = answer.items.filter { known.add(it.id) }
if (fresh.isEmpty()) more(app) else items = items + fresh
}
}, "gamejolt-browse").start()
}
}
@@ -0,0 +1,85 @@
package com.droiddeck.launcher.stores.gamejolt
import android.content.Context
import com.droiddeck.launcher.stores.CatalogItem
import org.json.JSONArray
import org.json.JSONObject
internal class GameJoltBuild(
val id: String,
val packageId: String,
val packageTitle: String,
val version: String,
val filename: String,
val size: Long,
val stamp: String,
val platforms: Set<String>,
val folder: String,
val executable: String,
) {
val installable: Boolean get() = "windows" in platforms
}
internal object GameJoltBuilds {
fun parse(payload: JSONObject?): List<GameJoltBuild> {
if (payload == null) return emptyList()
val packages = objects(payload.optJSONArray("packages")).associate { it.optLong("id") to it.optString("title") }
val releases = objects(payload.optJSONArray("releases")).associateBy { it.optLong("id") }
val launch = objects(payload.optJSONArray("launchOptions"))
val builds = objects(payload.optJSONArray("builds")).filter { it.optJSONObject("primary_file") != null }
val newest = builds.groupBy { it.optLong("game_package_id") }.mapValues { (_, list) ->
list.maxOfOrNull { releaseRank(releases[it.optLong("game_release_id")], it.optLong("game_release_id")) }
}
return builds
.filter { newest[it.optLong("game_package_id")] == releaseRank(releases[it.optLong("game_release_id")], it.optLong("game_release_id")) }
.map { build ->
val file = build.optJSONObject("primary_file")
val release = releases[build.optLong("game_release_id")]
val id = build.optLong("id")
GameJoltBuild(
id = id.toString(),
packageId = build.optLong("game_package_id").toString(),
packageTitle = packages[build.optLong("game_package_id")].orEmpty(),
version = release?.optString("version_number").orEmpty(),
filename = file?.optString("filename").orEmpty().substringAfterLast('/').substringAfterLast('\\'),
size = file?.optLong("filesize") ?: 0L,
stamp = release?.optLong("published_on")?.takeIf { it > 0L }?.toString().orEmpty(),
platforms = platforms(build),
folder = build.optString("folder"),
executable = launch.firstOrNull { it.optLong("game_build_id") == id && it.optString("os").startsWith("windows") }?.optString("executable_path").orEmpty(),
)
}
.sortedWith(compareByDescending<GameJoltBuild> { it.installable }.thenByDescending { it.stamp.toLongOrNull() ?: 0L }.thenByDescending { it.id.toLongOrNull() ?: 0L })
}
fun platforms(build: JSONObject): Set<String> {
val found = LinkedHashSet<String>()
if (build.optBoolean("os_windows") || build.optBoolean("os_windows_64")) found.add("windows")
if (build.optBoolean("os_linux") || build.optBoolean("os_linux_64")) found.add("linux")
if (build.optBoolean("os_mac") || build.optBoolean("os_mac_64")) found.add("osx")
if (build.optBoolean("os_other")) found.add("other")
return if (found.isEmpty()) setOf("web") else found
}
fun load(context: Context, gameId: String): List<GameJoltBuild>? {
val answer = GameJoltApi.overview(gameId, GameJoltAuth.cookies(context))
if (!answer.ok) return null
return parse(answer.payload)
}
fun byId(builds: List<GameJoltBuild>, id: String): GameJoltBuild? = builds.firstOrNull { it.id == id }
fun preferred(builds: List<GameJoltBuild>): GameJoltBuild? = builds.firstOrNull { it.installable }
fun size(context: Context, item: CatalogItem): Long {
val gameId = item.extra["gameId"].orEmpty().ifEmpty { item.id }
val builds = load(context, gameId) ?: return 0L
val chosen = item.extra["buildId"]?.let { byId(builds, it) } ?: preferred(builds)
return chosen?.size ?: 0L
}
private fun releaseRank(release: JSONObject?, id: Long): Long = (release?.optLong("published_on") ?: 0L) * 1_000_000L + id
private fun objects(array: JSONArray?): List<JSONObject> =
if (array == null) emptyList() else (0 until array.length()).mapNotNull { array.optJSONObject(it) }
}
@@ -0,0 +1,76 @@
package com.droiddeck.launcher.stores.gamejolt
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.cleanStoreText
import org.json.JSONArray
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import java.util.concurrent.atomic.AtomicBoolean
internal object GameJoltCatalog {
private const val PAID = "paid"
private val sellableLogged = AtomicBoolean(false)
fun items(games: JSONArray?, owned: Boolean = false): List<CatalogItem> {
if (games == null) return emptyList()
return (0 until games.length()).mapNotNull { games.optJSONObject(it)?.let { game -> item(game, owned) } }.distinctBy { it.id }
}
fun item(game: JSONObject, owned: Boolean = false): CatalogItem? {
val id = game.optLong("id")
if (id <= 0L) return null
val slug = game.optString("slug")
val sellable = game.optJSONObject("sellable")
val paid = sellable?.optString("type") == PAID
if (paid) noteSellable(sellable)
val developer = game.optJSONObject("developer")
val author = developer?.optString("display_name").orEmpty().ifBlank { developer?.optString("username").orEmpty() }
val thumbnail = game.optJSONObject("thumbnail_media_item")?.optString("img_url").orEmpty().ifBlank { game.optString("img_thumbnail") }
val header = game.optJSONObject("header_media_item")?.optString("img_url").orEmpty().ifBlank { game.optString("img_thumbnail") }
val price = if (paid) GameJoltPricing.of(sellable) else null
val compatibility = game.optJSONObject("compatibility")
val tags = buildList {
if (compatibility?.optBoolean("os_windows") == true) add("Windows")
if (compatibility?.optBoolean("os_linux") == true) add("Linux")
if (compatibility?.optBoolean("os_mac") == true) add("macOS")
}.joinToString(", ")
return CatalogItem(
store = Store.GAMEJOLT,
id = id.toString(),
title = game.optString("title").ifBlank { "Game Jolt game $id" },
imageUrl = header.ifBlank { null },
tallImageUrl = thumbnail.ifBlank { null },
tags = tags,
isFree = !paid,
hasPrice = paid,
finalPrice = price?.final.orEmpty(),
originalPrice = price?.original.orEmpty(),
discountPercent = price?.discount ?: 0,
owned = owned,
storeUrl = GameJoltApi.pageUrl(slug.ifBlank { "game" }, id.toString()),
developer = author,
publisher = author,
releaseDate = date(game.optLong("published_on")),
description = cleanStoreText(game.optString("description")),
mature = game.optBoolean("has_adult_content"),
extra = mapOf("gameId" to id.toString(), "slug" to slug),
)
}
private fun noteSellable(sellable: JSONObject?) {
if (sellable == null || !sellableLogged.compareAndSet(false, true)) return
val pricing = sellable.optJSONArray("pricings")?.optJSONObject(0)
StoresState.logLine("Game Jolt: a paid game carries sellable keys [${sellable.keys().asSequence().joinToString(",")}] and pricing keys [${pricing?.keys()?.asSequence()?.joinToString(",").orEmpty()}]")
}
private fun date(stamp: Long): String {
if (stamp <= 0L) return ""
val millis = if (stamp > 100_000_000_000L) stamp else stamp * 1000L
return SimpleDateFormat("yyyy-MM-dd", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }.format(Date(millis))
}
}
@@ -0,0 +1,120 @@
package com.droiddeck.launcher.stores.gamejolt
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONArray
import org.json.JSONObject
import java.net.URLEncoder
import java.util.concurrent.ConcurrentHashMap
internal class GameJoltCollection(val id: String, val title: String)
internal object GameJoltCollections {
const val FOLLOWED = "followed"
private const val PLAYLIST = "playlist:"
var list by mutableStateOf<List<GameJoltCollection>>(emptyList())
private set
var selected by mutableStateOf<String?>(null)
private set
private val games = mutableStateMapOf<String, List<CatalogItem>>()
private val loading = ConcurrentHashMap.newKeySet<String>()
@Volatile private var generation = 0
fun items(): List<CatalogItem> = games.values.flatten()
fun gamesOf(id: String): List<CatalogItem>? = games[id]
fun chosen(): GameJoltCollection? = list.firstOrNull { it.id == selected }
fun clear() {
generation++
StoresState.post {
list = emptyList()
selected = null
games.clear()
}
}
fun load(context: Context) {
val app = context.applicationContext
val started = generation
val guard = "$started:"
if (!loading.add(guard)) return
Thread({
try {
val cookies = GameJoltAuth.cookies(app)
if (cookies.isBlank()) return@Thread
val playlists = playlists(cookies) ?: return@Thread
val parsed = listOf(GameJoltCollection(FOLLOWED, app.getString(R.string.stores_gamejolt_followed))) + parse(playlists)
if (started != generation) return@Thread
StoresState.post {
if (started != generation) return@post
list = parsed
if (selected != null && parsed.none { it.id == selected }) selected = null
}
StoresState.logLine("Game Jolt: ${parsed.size} collections")
selected?.let { fetchGames(app, it, started) }
} finally {
loading.remove(guard)
}
}, "gamejolt-collections").start()
}
fun select(context: Context, id: String?) {
selected = id
if (id == null) return
val app = context.applicationContext
val started = generation
Thread({ fetchGames(app, id, started) }, "gamejolt-collection-games").start()
}
private fun playlists(cookies: String): JSONArray? {
val library = GameJoltApi.get("/web/library", cookies)
if (!library.ok) return null
library.payload?.optJSONArray("playlists")?.let { return it }
val nested = library.payload?.optJSONArray("collections")
if (nested != null) {
val out = JSONArray()
for (i in 0 until nested.length()) nested.optJSONObject(i)?.optJSONObject("playlist")?.let { out.put(it) }
if (out.length() > 0) return out
}
return GameJoltApi.get("/web/library/playlists", cookies).takeIf { it.ok }?.payload?.optJSONArray("playlists") ?: JSONArray()
}
internal fun parse(playlists: JSONArray): List<GameJoltCollection> = (0 until playlists.length()).mapNotNull { i ->
val playlist = playlists.optJSONObject(i) ?: return@mapNotNull null
val id = playlist.optLong("id").takeIf { it > 0L } ?: return@mapNotNull null
val title = playlist.optString("name").ifBlank { return@mapNotNull null }
GameJoltCollection("$PLAYLIST$id", title)
}
internal fun path(id: String, username: String): String? = when {
id == FOLLOWED -> "/web/library/games/followed/@${URLEncoder.encode(username, "UTF-8")}"
id.startsWith(PLAYLIST) -> id.removePrefix(PLAYLIST).toLongOrNull()?.let { "/web/library/games/playlist/$it" }
else -> null
}
private fun fetchGames(app: Context, id: String, started: Int) {
val guard = "$started:$id"
if (!loading.add(guard)) return
try {
val path = path(id, GameJoltAuth.username(app)) ?: return
val found = GameJoltLibrary.games(app, path, false)
if (found == null) {
StoresState.logLine("Game Jolt: collection $id failed")
return
}
StoresState.post { if (started == generation) games[id] = found }
StoresState.logLine("Game Jolt: collection $id has ${found.size} games")
} finally {
loading.remove(guard)
}
}
}
@@ -0,0 +1,239 @@
package com.droiddeck.launcher.stores.gamejolt
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreArchiveUnpacker
import com.droiddeck.launcher.stores.StoreExe
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreNet
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.itch.ItchArchives
import com.droiddeck.launcher.stores.itch.ItchStaging
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.atomic.AtomicBoolean
internal class GameJoltInstaller(
private val app: Context,
private val item: CatalogItem,
private val folder: File,
) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private var work: File = folder
private var updating = false
private var previous: StoreGameSidecar? = null
private val commit = Any()
private val unpacker = StoreArchiveUnpacker(app, cancelled, "Game Jolt", R.string.stores_gamejolt_archive, R.string.stores_gamejolt_extract_failed, "gamejolt-unrar")
override fun run(handle: DownloadQueue.JobHandle): String? {
val cookies = GameJoltAuth.cookies(app)
if (cookies.isBlank()) throw IllegalStateException(app.getString(R.string.stores_sync_sign_in))
if (!item.isFree && !item.owned) throw IllegalStateException(app.getString(R.string.stores_gamejolt_not_owned))
val gameId = item.extra["gameId"].orEmpty().ifEmpty { item.id }
val before = StoreGameSidecar.read(folder)
previous = before
updating = before != null && (before.isInstalled || before.state == StoreGameSidecar.STATE_UPDATING)
val resuming = before?.let { it.state == StoreGameSidecar.STATE_INSTALLING && it.id == item.id } == true
StoreInstalls.begin(folder, Store.GAMEJOLT, item.id, item.title, item.imageUrl, item.imageUrl)
handle.stage(DownloadStage.MANIFEST)
val builds = GameJoltBuilds.load(app, gameId) ?: throw IllegalStateException(app.getString(R.string.stores_gamejolt_no_game))
val chosen = item.extra["buildId"].orEmpty()
val build = (if (chosen.isBlank()) GameJoltBuilds.preferred(builds) else GameJoltBuilds.byId(builds, chosen))?.takeIf { it.installable }
?: throw IllegalStateException(app.getString(R.string.stores_gamejolt_no_build))
handle.log("Game Jolt: installing build ${build.id} (${build.filename}, ${build.size} bytes, platforms ${build.platforms.joinToString(",")}, launch ${build.executable.ifBlank { "none" }})")
val scratch = StoreInstallRoot.scratchDir(app, Store.GAMEJOLT, item.id)
scratch.mkdirs()
val filename = build.filename.trim().takeUnless { it.isBlank() || it == "." || it == ".." } ?: "download.bin"
val archive = File(scratch, filename)
val exe = try {
handle.stage(DownloadStage.DOWNLOAD)
download(build, archive, handle)
if (cancelled.get()) return null
handle.stage(DownloadStage.INSTALL)
install(build, archive, filename, handle, resuming)
} catch (t: Throwable) {
if (!cancelled.get()) dropCaches(scratch)
throw t
}
if (exe == null) {
if (cancelled.get()) return null
dropCaches(scratch)
throw IllegalStateException(app.getString(R.string.stores_gamejolt_no_exe))
}
archive.delete()
StoreInstalls.deleteTree(scratch)
val sidecar = StoreGameSidecar(
store = Store.GAMEJOLT,
id = item.id,
title = item.title,
exe = exe,
args = previous?.args.orEmpty(),
env = previous?.env.orEmpty(),
installVersion = build.stamp,
installedAt = System.currentTimeMillis(),
cover = item.imageUrl,
hero = item.imageUrl,
extra = mapOf("gameId" to gameId, "buildId" to build.id, "packageId" to build.packageId) + (if (item.isFree) emptyMap() else mapOf("paid" to "1")),
cloud = false,
)
StoreInstalls.complete(app, folder, sidecar) { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }
GameJoltUpdates.applied(app, item.key)
return folder.path
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (deleteFiles) dropCaches(StoreInstallRoot.scratchDir(app, Store.GAMEJOLT, item.id))
}
private fun dropCaches(scratch: File) {
if (!updating) {
StoreInstalls.discard(app, folder, listOf(scratch))
return
}
synchronized(commit) {
StoreInstalls.deleteTree(scratch)
ItchStaging.delete(File(folder, ItchStaging.DIR))
}
}
private fun download(build: GameJoltBuild, target: File, handle: DownloadQueue.JobHandle) {
val origin = File(target.path + ".from")
val stamp = "${build.id} ${build.stamp} ${build.size}"
if (!target.isFile || runCatching { origin.readText() }.getOrNull() != stamp) {
target.delete()
origin.writeText(stamp)
}
val expected = build.size
if (expected > 0 && target.length() == expected) {
handle.progress(expected, expected)
return
}
for (attempt in 0..1) {
val have = target.length()
val url = downloadLink(build)
var conn: HttpURLConnection? = null
try {
conn = (URL(url).openConnection() as HttpURLConnection).apply {
connectTimeout = 30_000
readTimeout = 60_000
instanceFollowRedirects = true
setRequestProperty("User-Agent", StoreNet.BROWSER_UA)
setRequestProperty("Accept", "*/*")
if (have > 0) setRequestProperty("Range", "bytes=$have-")
}
val code = conn.responseCode
if (code == 416 && attempt == 0) {
target.delete()
continue
}
if (code !in 200..299) throw IllegalStateException(app.getString(R.string.stores_gamejolt_download_failed, code))
val append = code == 206 && have > 0
if (have > 0) handle.log(if (append) "Game Jolt: resuming at $have bytes" else "Game Jolt: server ignored the resume, starting over")
var done = if (append) have else 0L
val total = conn.contentLengthLong.takeIf { it > 0 }?.let { if (append) it + have else it } ?: expected
handle.progress(done, total)
val buffer = ByteArray(128 * 1024)
conn.inputStream.use { input ->
FileOutputStream(target, append).use { out ->
while (true) {
if (cancelled.get()) return
val read = input.read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
done += read
handle.progress(done, total)
}
}
}
if (total > 0 && done < total) throw IllegalStateException(app.getString(R.string.stores_gamejolt_download_failed, code))
return
} finally {
runCatching { conn?.disconnect() }
}
}
}
private fun downloadLink(build: GameJoltBuild): String {
val answer = GameJoltApi.post("/web/discover/games/builds/get-download-url/${build.id}", GameJoltAuth.cookies(app))
val url = answer.payload?.optString("url").orEmpty()
if (url.startsWith("https://")) return url
throw IllegalStateException(
when {
answer.code == 0 -> app.getString(R.string.stores_gamejolt_download_unreachable)
answer.ok -> app.getString(R.string.stores_gamejolt_download_no_link)
else -> app.getString(R.string.stores_gamejolt_download_failed, answer.code)
},
)
}
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(build: GameJoltBuild, archive: File, filename: String, handle: DownloadQueue.JobHandle, resuming: Boolean): String? {
work = if (updating) File(folder, ItchStaging.DIR) else folder
if (updating) ItchStaging.delete(work)
work.mkdirs()
unpacker.work = work
if (resuming) clearPartialInstall()
val exe = try {
val kind = ItchArchives.kind(archive, filename)
if (kind == "exe") archive.copyTo(File(work, filename), overwrite = true) else unpacker.unpack(archive, filename, handle)
var picked = pick(build, filename)
var passes = 0
while (picked.isBlank() && passes < 2 && !cancelled.get()) {
val inner = ItchArchives.inner(work) ?: break
handle.log("Game Jolt: no exe yet, unpacking ${inner.name}")
unpacker.unpack(inner, inner.name, handle)
if (cancelled.get()) break
inner.delete()
picked = pick(build, inner.name.substringBeforeLast('.').takeIf { it.endsWith(".exe", ignoreCase = true) })
passes++
}
picked
} catch (t: Throwable) {
if (updating) ItchStaging.delete(work)
throw t
}
if (exe.isBlank()) {
handle.log("Game Jolt: no exe found in ${folder.name}")
if (updating) ItchStaging.delete(work)
return null
}
if (updating) synchronized(commit) {
if (cancelled.get()) {
ItchStaging.delete(work)
return null
}
try {
StoreInstalls.markUpdating(folder)
} catch (t: Throwable) {
ItchStaging.delete(work)
throw t
}
ItchStaging.merge(work, folder)
ItchStaging.delete(work)
}
return exe
}
private fun pick(build: GameJoltBuild, hint: String?): String {
if (build.executable.isNotBlank()) {
val declared = File(work, build.executable.trimStart('/'))
val inside = runCatching { declared.canonicalPath.startsWith(work.canonicalPath + File.separator) }.getOrDefault(false)
if (inside && declared.isFile) return declared.relativeTo(work).path
}
return StoreExe.pick(work, hint?.ifBlank { null } ?: build.filename.substringBeforeLast('.').ifBlank { null }, item.title)
}
}
@@ -0,0 +1,74 @@
package com.droiddeck.launcher.stores.gamejolt
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.mergeItems
import java.net.URLEncoder
import java.util.concurrent.atomic.AtomicBoolean
internal object GameJoltLibrary {
private const val MAX_PAGES = 20
private const val THROTTLE_MS = 10 * 60 * 1000L
private val running = AtomicBoolean(false)
@Volatile private var syncedAt = 0L
fun sync(context: Context, force: Boolean) {
val app = context.applicationContext
if (!running.compareAndSet(false, true)) return
try {
val cookies = GameJoltAuth.cookies(app)
val name = GameJoltAuth.username(app)
if (cookies.isBlank() || name.isBlank()) {
StoresState.post {
StoresState.status.remove(Store.GAMEJOLT)
StoresState.problems[Store.GAMEJOLT] = app.getString(R.string.stores_sync_sign_in)
}
return
}
val have = StoresState.library[Store.GAMEJOLT].orEmpty()
if (!force && have.isNotEmpty() && System.currentTimeMillis() - syncedAt < THROTTLE_MS) return
if (have.isEmpty()) StoresState.post { StoresState.status[Store.GAMEJOLT] = app.getString(R.string.stores_sync_game_list) }
val items = games(app, "/web/library/games/owned/@${URLEncoder.encode(name, "UTF-8")}", true)
if (items == null) {
StoresState.post {
StoresState.status.remove(Store.GAMEJOLT)
StoresState.problems[Store.GAMEJOLT] = app.getString(R.string.stores_sync_failed)
}
return
}
syncedAt = System.currentTimeMillis()
StoresState.post {
StoresState.status.remove(Store.GAMEJOLT)
StoresState.problems.remove(Store.GAMEJOLT)
StoresState.library[Store.GAMEJOLT] = mergeItems(StoresState.library[Store.GAMEJOLT], items)
}
StoresState.logLine("Game Jolt: ${items.size} owned games")
} finally {
running.set(false)
}
}
fun reset() {
syncedAt = 0L
}
fun games(context: Context, path: String, owned: Boolean): List<CatalogItem>? {
val cookies = GameJoltAuth.cookies(context)
val out = ArrayList<CatalogItem>()
val seen = HashSet<String>()
for (page in 1..MAX_PAGES) {
val answer = GameJoltApi.get(if (page == 1) path else "$path?page=$page", cookies)
if (!answer.ok) return if (page == 1) null else out
val batch = GameJoltCatalog.items(answer.payload?.optJSONArray("games"), owned).filter { seen.add(it.id) }
if (batch.isEmpty()) break
out.addAll(batch)
val total = answer.payload?.optInt("totalGamesCount") ?: 0
if (total in 1..out.size) break
}
return out
}
}
@@ -0,0 +1,55 @@
package com.droiddeck.launcher.stores.gamejolt
import android.net.Uri
import android.util.Log
import android.webkit.CookieManager
import android.webkit.WebView
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.WebCookies
internal class GameJoltLogin(override val userAgent: String) : StoreLoginActivity.Flow {
override val startUrl: String get() = GameJoltApi.LOGIN
override fun isRedirect(url: String): Boolean {
val uri = Uri.parse(url)
if (uri.host != HOST && uri.host != "www.$HOST") return false
val path = uri.path.orEmpty()
return AUTH_PATHS.none { path == it || path.startsWith("$it/") }
}
override fun forgetSignIn(done: () -> Unit) {
runCatching { WebCookies.expire(listOf(GameJoltApi.SITE), HOST, listOf("/")) { done() } }
.onFailure {
Log.w(TAG, "could not clear the previous web sign-in: ${it.javaClass.simpleName}")
done()
}
}
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
val manager = CookieManager.getInstance()
manager.flush()
val cookies = manager.getCookie(GameJoltApi.SITE).orEmpty()
if (cookies.isBlank()) {
Log.w(TAG, "no cookies after the sign-in redirect")
return activity.getString(R.string.stores_login_error_verification)
}
val answer = GameJoltApi.get("/web/search/games?q=a", cookies)
val user = answer.user
Log.d(TAG, "verify: code=${answer.code} cookies=${cookies.split(';').joinToString(",") { it.substringBefore('=').trim() }} userKeys=${user?.keys()?.asSequence()?.joinToString(",").orEmpty()}")
if (user == null || user.optLong("id") <= 0L) return activity.getString(R.string.stores_login_error_verification)
return try {
GameJoltAuth.save(activity, cookies, user)
null
} catch (e: Exception) {
Log.w(TAG, "saving the sign-in failed: ${e.javaClass.simpleName}")
activity.getString(R.string.stores_login_error_generic)
}
}
companion object {
private const val TAG = "GameJoltLogin"
private const val HOST = "gamejolt.com"
private val AUTH_PATHS = listOf("/login", "/join", "/auth", "/forgot", "/terms", "/privacy", "/help", "/legal", "/site-api", "/x", "/oauth")
}
}
@@ -0,0 +1,11 @@
package com.droiddeck.launcher.stores.gamejolt
import android.content.Context
import android.content.SharedPreferences
object GameJoltPrefs {
const val FILE = "stores.gamejolt"
@JvmStatic
fun get(context: Context): SharedPreferences = context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
}
@@ -0,0 +1,28 @@
package com.droiddeck.launcher.stores.gamejolt
import org.json.JSONObject
import java.util.Locale
internal object GameJoltPricing {
class Price(val final: String, val original: String, val discount: Int)
fun of(sellable: JSONObject?): Price? {
val list = sellable?.optJSONArray("pricings") ?: return null
val entries = (0 until list.length()).mapNotNull { list.optJSONObject(it) }.filter { it.optLong("amount") > 0L }
val sale = entries.firstOrNull { it.optBoolean("promotional") }
val regular = entries.firstOrNull { !it.optBoolean("promotional") }
val now = sale ?: regular ?: return null
val was = if (sale != null && regular != null && regular.optLong("amount") > sale.optLong("amount")) regular else null
val percent = if (was == null) 0 else {
val before = was.optLong("amount")
(((before - now.optLong("amount")) * 100 + before / 2) / before).toInt()
}
return Price(format(now), was?.let(::format).orEmpty(), percent)
}
private fun format(pricing: JSONObject): String {
val amount = String.format(Locale.US, "%.2f", pricing.optLong("amount") / 100.0)
val currency = pricing.optString("currency_code").takeIf { it.isNotBlank() && it != "null" && !it.equals("USD", ignoreCase = true) }
return if (currency == null) "$$amount" else "$amount $currency"
}
}
@@ -0,0 +1,188 @@
package com.droiddeck.launcher.stores.gamejolt
import android.content.Context
import android.widget.Toast
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONObject
import java.util.concurrent.atomic.AtomicBoolean
internal class GameJoltUpdate(val buildId: String, val stamp: String, val filename: String, val replaced: Boolean)
internal object GameJoltUpdates {
private const val KEY_AT = "updates_checked_at"
private const val KEY_FOUND = "updates_found"
private const val THROTTLE_MS = 6 * 60 * 60 * 1000L
private const val GAP_MS = 1_000L
val available = mutableStateMapOf<String, GameJoltUpdate>()
var checkingKey by mutableStateOf<String?>(null)
private set
private val running = AtomicBoolean(false)
private val restored = AtomicBoolean(false)
@Volatile private var generation = 0
internal fun evaluate(builds: List<GameJoltBuild>?, buildId: String, packageId: String, version: String): GameJoltUpdate? {
if (builds == null || buildId.isBlank()) return null
val installable = builds.filter { it.installable }
val samePackage = installable.filter { it.packageId == packageId }
if (samePackage.isNotEmpty()) {
if (samePackage.any { it.id == buildId }) return null
val same = samePackage.firstOrNull { newer(it, buildId, version) } ?: return null
return GameJoltUpdate(same.id, same.stamp, same.filename, false)
}
val next = installable.firstOrNull() ?: return null
return if (next.id == buildId) null else GameJoltUpdate(next.id, next.stamp, next.filename, true)
}
private fun newer(build: GameJoltBuild, buildId: String, version: String): Boolean {
val stamp = build.stamp.toLongOrNull() ?: 0L
val have = version.toLongOrNull() ?: 0L
if (stamp != have) return stamp > have
return (build.id.toLongOrNull() ?: 0L) > (buildId.toLongOrNull() ?: 0L)
}
internal fun encode(found: Map<String, GameJoltUpdate>): String = JSONObject().also { out ->
for ((key, u) in found) out.put(key, JSONObject().put("buildId", u.buildId).put("stamp", u.stamp).put("filename", u.filename).put("replaced", u.replaced))
}.toString()
internal fun decode(raw: String?): Map<String, GameJoltUpdate> {
val json = runCatching { JSONObject(raw.orEmpty()) }.getOrNull() ?: return emptyMap()
val out = LinkedHashMap<String, GameJoltUpdate>()
for (key in json.keys()) {
val u = json.optJSONObject(key) ?: continue
val id = u.optString("buildId")
if (id.isBlank()) continue
out[key] = GameJoltUpdate(id, u.optString("stamp"), u.optString("filename"), u.optBoolean("replaced"))
}
return out
}
private fun restore(app: Context) {
if (!restored.compareAndSet(false, true)) return
val started = generation
val saved = decode(GameJoltPrefs.get(app).getString(KEY_FOUND, null))
StoresState.post {
if (started != generation) return@post
for ((k, v) in saved) if (k !in available) available[k] = v
}
}
private fun save(app: Context) {
GameJoltPrefs.get(app).edit().putString(KEY_FOUND, encode(available.toMap())).apply()
}
private fun snapshot(game: InstalledStoreGame): Triple<String, String, String> =
Triple(game.sidecar.installVersion, game.sidecar.extra["buildId"].orEmpty(), game.sidecar.extra["packageId"].orEmpty())
fun check(context: Context) {
val app = context.applicationContext
if (!running.compareAndSet(false, true)) return
val started = generation
Thread({
try {
restore(app)
val prefs = GameJoltPrefs.get(app)
if (System.currentTimeMillis() - prefs.getLong(KEY_AT, 0L) < THROTTLE_MS) return@Thread
if (GameJoltAuth.cookies(app).isBlank()) return@Thread
val games = StoresState.installed.toList().filter { it.sidecar.store == Store.GAMEJOLT && it.sidecar.isInstalled }
val found = LinkedHashMap<String, GameJoltUpdate>()
val answered = HashSet<String>()
val seen = HashMap<String, Triple<String, String, String>>()
var failed = false
games.forEachIndexed { i, game ->
if (i > 0) Thread.sleep(GAP_MS)
val extra = game.sidecar.extra
seen[game.key] = snapshot(game)
val builds = GameJoltBuilds.load(app, extra["gameId"].orEmpty().ifEmpty { game.sidecar.id })
if (builds == null) failed = true
else {
answered += game.key
evaluate(builds, extra["buildId"].orEmpty(), extra["packageId"].orEmpty(), game.sidecar.installVersion)?.let { found[game.key] = it }
}
}
if (started != generation) return@Thread
StoresState.post {
if (started != generation) return@post
for (k in answered) {
val now = StoresState.installed.firstOrNull { it.key == k } ?: continue
if (seen[k] != snapshot(now)) continue
val u = found[k]
if (u != null) available[k] = u else available.remove(k)
}
save(app)
}
if (!failed && started == generation) prefs.edit().putLong(KEY_AT, System.currentTimeMillis()).apply()
StoresState.logLine("Game Jolt: checked ${games.size} installed games, ${found.size} with updates")
} finally {
running.set(false)
}
}, "gamejolt-updates").start()
}
fun checkGame(context: Context, game: InstalledStoreGame) {
val app = context.applicationContext
if (checkingKey != null) return
checkingKey = game.key
val started = generation
val before = snapshot(game)
Thread({
try {
val extra = game.sidecar.extra
val builds = GameJoltBuilds.load(app, extra["gameId"].orEmpty().ifEmpty { game.sidecar.id })
val found = evaluate(builds, before.second, before.third, before.first)
StoresState.post {
if (started != generation) return@post
val now = StoresState.installed.firstOrNull { it.key == game.key }
if (builds != null && now != null && snapshot(now) == before) {
if (found != null) available[game.key] = found else available.remove(game.key)
save(app)
}
val text = when {
builds == null -> app.getString(R.string.stores_sync_failed)
found != null -> app.getString(R.string.stores_itch_updates_found, 1)
else -> app.getString(R.string.upd_current_status)
}
Toast.makeText(app, text, Toast.LENGTH_SHORT).show()
}
StoresState.logLine("Game Jolt: checked ${game.sidecar.title}, ${if (found != null) "update available" else "up to date"}")
} finally {
StoresState.post { checkingKey = null }
}
}, "gamejolt-update-check").start()
}
fun start(context: Context, game: InstalledStoreGame, update: GameJoltUpdate) {
val app = context.applicationContext
if (StoresState.uninstalling.containsKey(game.key)) return
val root = game.folder.parentFile?.parentFile ?: return
val item = CatalogItem(
Store.GAMEJOLT, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover,
isFree = game.sidecar.extra["paid"] != "1", owned = true, extra = game.sidecar.extra + ("buildId" to update.buildId),
)
StoresState.install(app, item, root)
}
fun applied(context: Context, key: String) {
val app = context.applicationContext
StoresState.post {
available.remove(key)
save(app)
}
}
fun clear(context: Context) {
val app = context.applicationContext
generation++
GameJoltPrefs.get(app).edit().remove(KEY_AT).remove(KEY_FOUND).apply()
StoresState.post { available.clear() }
}
}
@@ -2,10 +2,9 @@ package com.droiddeck.launcher.stores.itch
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreArchiveUnpacker
import com.droiddeck.launcher.stores.StoreExe
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
@@ -13,20 +12,10 @@ import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreNet
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.apache.commons.compress.MemoryLimitException
import org.apache.commons.compress.archivers.sevenz.SevenZFile
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import org.apache.commons.compress.archivers.zip.ZipFile
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.nio.file.Files
import java.util.concurrent.atomic.AtomicBoolean
internal class ItchInstaller(
@@ -39,6 +28,7 @@ internal class ItchInstaller(
private var updating = false
private var previous: StoreGameSidecar? = null
private val commit = Any()
private val unpacker = StoreArchiveUnpacker(app, cancelled, "itch.io", R.string.stores_itch_archive, R.string.stores_itch_extract_failed, "itch-unrar")
override fun run(handle: DownloadQueue.JobHandle): String? {
val key = ItchAuth.key(app)
@@ -225,16 +215,17 @@ internal class ItchInstaller(
work = if (updating) File(folder, ItchStaging.DIR) else folder
if (updating && !patched) ItchStaging.delete(work)
work.mkdirs()
unpacker.work = work
if (resuming) clearPartialInstall()
val exe = try {
if (!patched) unpack(archive, filename, handle)
if (!patched) unpacker.unpack(archive, filename, handle)
val hint = filename.substringBeforeLast('.')
var picked = StoreExe.pick(work, hint.ifBlank { null }, item.title)
var passes = 0
while (picked.isBlank() && passes < 2 && !cancelled.get()) {
val inner = ItchArchives.inner(work) ?: break
handle.log("itch.io: no exe yet, unpacking ${inner.name}")
unpack(inner, inner.name, handle)
unpacker.unpack(inner, inner.name, handle)
if (cancelled.get()) break
inner.delete()
picked = StoreExe.pick(work, inner.name.substringBeforeLast('.').takeIf { it.endsWith(".exe", ignoreCase = true) }, item.title)
@@ -267,205 +258,5 @@ internal class ItchInstaller(
return exe
}
private fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) {
when (val kind = ItchArchives.kind(archive, filename)) {
"zip" -> unzip(archive, handle)
"7z" -> try {
sevenZip(archive, handle)
} catch (e: MemoryLimitException) {
handle.log("itch.io: ${archive.name} needs more memory than the app has, unpacking it in the runtime")
unrar(archive, handle, kind)
}
"rar" -> unrar(archive, handle, kind)
"exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" }))
"tar" -> untar(archive, null, handle)
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
else -> copy(archive, File(work, filename.ifBlank { "game" }))
}
}
private fun target(name: String): File? {
val file = File(work, name.replace('\\', '/'))
val root = work.canonicalPath
val path = file.canonicalPath
return if (path == root || path.startsWith(root + File.separator)) file else null
}
private fun unrar(archive: File, handle: DownloadQueue.JobHandle, kind: String) {
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(R.string.stores_itch_archive, kind))
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
else listOf(work.absolutePath)
fun bsdtar(args: List<String>, onLine: (String) -> Unit) =
GuestCommand.run(app, listOf("/usr/bin/bsdtar") + args, logName = "itch-unrar", extraBinds = binds, fastPath = true, cancelled = cancelled) { line ->
if (!line.startsWith("proot ")) onLine(line)
}
var entries = 0L
bsdtar(listOf("-tf", archive.absolutePath)) { entries++ }
var done = 0L
val tail = ArrayDeque<String>()
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line ->
if (line.startsWith("x ")) handle.stageProgress(++done, entries) else {
if (tail.size == 5) tail.removeFirst()
tail.addLast(line)
}
}
if (cancelled.get()) return
if (code != 0) {
handle.log("itch.io: bsdtar exited $code: ${tail.joinToString(" | ")}")
throw IllegalStateException(app.getString(R.string.stores_itch_extract_failed, code))
}
}
private fun sevenZip(archive: File, handle: DownloadQueue.JobHandle) {
val total = archive.length()
var written = 0L
val buffer = ByteArray(64 * 1024)
val limitKb = (Runtime.getRuntime().maxMemory() / 4 / 1024).coerceIn(32L * 1024, Int.MAX_VALUE.toLong()).toInt()
Files.newByteChannel(archive.toPath()).use { channel ->
SevenZFile.builder().setSeekableByteChannel(channel).setMaxMemoryLimitKb(limitKb).get().use { seven ->
while (true) {
if (cancelled.get()) return
val entry = seven.nextEntry ?: break
val file = target(entry.name)
if (file == null) {
handle.log("itch.io: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
file.mkdirs()
continue
}
file.parentFile?.mkdirs()
FileOutputStream(file).use { out ->
while (true) {
if (cancelled.get()) return
val read = seven.read(buffer, 0, buffer.size)
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
}
}
}
}
}
}
private fun untar(archive: File, codec: String?, handle: DownloadQueue.JobHandle): Unit? {
val total = archive.length()
var written = 0L
var entries = 0
val buffer = ByteArray(64 * 1024)
val opened = runCatching {
FileInputStream(archive).use { raw ->
val stream = when (codec) {
"gz" -> GzipCompressorInputStream(BufferedInputStream(raw))
"bz2" -> BZip2CompressorInputStream(BufferedInputStream(raw))
"xz" -> XZCompressorInputStream(BufferedInputStream(raw))
else -> BufferedInputStream(raw)
}
stream.use { input ->
TarArchiveInputStream(input).use { tar ->
while (true) {
if (cancelled.get()) return null
val entry = tar.nextEntry ?: break
entries++
val file = target(entry.name)
if (file == null) {
handle.log("itch.io: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
file.mkdirs()
continue
}
file.parentFile?.mkdirs()
FileOutputStream(file).use { out ->
while (true) {
if (cancelled.get()) return null
val read = tar.read(buffer, 0, buffer.size)
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
}
}
}
}
}
}
true
}
if (opened.isSuccess && entries > 0) return Unit
if (opened.isFailure && codec == null) throw opened.exceptionOrNull() ?: IllegalStateException("tar")
return null
}
private fun single(archive: File, codec: String, handle: DownloadQueue.JobHandle) {
val name = archive.name.substringBeforeLast('.')
val file = target(name.ifBlank { "game" }) ?: throw IllegalStateException("archive")
file.parentFile?.mkdirs()
val total = archive.length()
var written = 0L
val buffer = ByteArray(64 * 1024)
FileInputStream(archive).use { raw ->
val stream = when (codec) {
"bz2" -> BZip2CompressorInputStream(BufferedInputStream(raw))
"xz" -> XZCompressorInputStream(BufferedInputStream(raw))
else -> GzipCompressorInputStream(BufferedInputStream(raw))
}
stream.use { input ->
FileOutputStream(file).use { out ->
while (true) {
if (cancelled.get()) return
val read = input.read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
}
}
}
}
}
private fun copy(source: File, target: File) {
target.parentFile?.mkdirs()
FileInputStream(source).use { input -> FileOutputStream(target).use { out -> input.copyTo(out, 128 * 1024) } }
}
private fun unzip(archive: File, handle: DownloadQueue.JobHandle) {
val total = archive.length()
var written = 0L
val buffer = ByteArray(64 * 1024)
ZipFile.builder().setFile(archive).get().use { zip ->
for (entry in zip.entries) {
if (cancelled.get()) return
val target = target(entry.name)
if (target == null) {
handle.log("itch.io: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
target.mkdirs()
continue
}
target.parentFile?.mkdirs()
zip.getInputStream(entry).use { input ->
FileOutputStream(target).use { out ->
while (true) {
if (cancelled.get()) return
val read = input.read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
}
}
}
}
}
}
private companion object
}
@@ -701,6 +701,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
StoreTheme(com.droiddeck.launcher.stores.Store.XBOX) { XboxStoreDialogs() }
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 } } }
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
StepsLayer(screenAt)
appToChooseDisplay?.let { app ->
@@ -98,6 +98,7 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoreSizes
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.gamejolt.GameJoltApi
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadState
@@ -139,7 +140,7 @@ internal enum class GameTab { ABOUT, ACHIEVEMENTS, LAUNCH, SAVES, INSTALL }
@Composable
internal fun GameDetail(
key: String, s: FrontEndState, a: FrontEndActions, lead: FocusRequester, backLabel: String, hopRail: String?, onBack: () -> Unit,
key: String, s: FrontEndState, a: FrontEndActions, lead: FocusRequester, backLabel: String, hopRail: String?, onBack: () -> Unit, inStore: Boolean = false,
) {
val narrow = LocalNarrowPane.current
val stacked = narrow || LocalConfiguration.current.screenWidthDp < 700
@@ -218,6 +219,7 @@ internal fun GameDetail(
if (!s.shortcutPicker) CompositionLocalProvider(LocalPillButtons provides true) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (installed != null && installed.sidecar.store == Store.ITCH) ItchCheckButton(installed)
if (installed != null && installed.sidecar.store == Store.GAMEJOLT) GameJoltCheckButton(installed)
RemoveButton(title, game, installed, a)
}
}
@@ -232,7 +234,7 @@ internal fun GameDetail(
color = MaterialTheme.colorScheme.error, maxLines = 3, overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(2.dp))
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked) }
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore) }
}
}
if (StoresMotion.heroLands) header() else Rise(1) { header() }
@@ -382,7 +384,7 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) {
@Composable
internal fun GameActions(
store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?,
s: FrontEndState, a: FrontEndActions, leadOn: Modifier, compactMenu: Boolean = false,
s: FrontEndState, a: FrontEndActions, leadOn: Modifier, compactMenu: Boolean = false, inStore: Boolean = false,
) {
val ctx = LocalContext.current
val storeKey = if (store != null && id != null) "${store.id}:$id" else null
@@ -409,10 +411,16 @@ internal fun GameActions(
if (compactMenu) GameMoreMenu(game, a) else {
FileButtons(game, a)
GameShortcutMenu(game, a)
EditArtButton(game)
}
}
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GAMEJOLT && installed != null) GameJoltUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GAMEJOLT && installed != null) GameJoltVersionButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (inStore && store == Store.GAMEJOLT && installed != null) {
SecondaryButton(stringResource(R.string.stores_view_on, Store.GAMEJOLT.shortLabel)) {
openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) })
}
}
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) {
@@ -435,6 +443,7 @@ internal fun GameActions(
}
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
}
if (game != null && !compactMenu) EditArtButton(game)
}
download != null -> {
ActionChip(downloadLabel(download), ok = false)
@@ -482,7 +491,7 @@ internal fun GameActions(
}
if (!item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) }
}
item != null && item.store == Store.ITCH && item.isFree -> {
item != null && (item.store == Store.ITCH || item.store == Store.GAMEJOLT) && 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) }
}
@@ -0,0 +1,157 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.gamejolt.GameJoltBrowse
import com.droiddeck.launcher.stores.gamejolt.GameJoltBrowseState
import com.droiddeck.launcher.stores.gamejolt.GameJoltQuery
@Composable
internal fun GameJoltBrowseBar(showMature: Boolean) {
val ctx = LocalContext.current
val query = GameJoltBrowseState.query
var picking by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { if (GameJoltBrowseState.items.isEmpty()) GameJoltBrowseState.more(ctx) }
fun toggle(set: Set<String>, value: String): Set<String> = if (value in set) set - value else set + value
Column(Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
ChipRow {
BrowseDropdown(sectionLabel(query.section)) { first, close ->
GameJoltBrowse.sections.forEachIndexed { index, section ->
MenuItem(sectionLabel(section), query.section == section, focusRequester = if (index == 0) first else null) {
GameJoltBrowseState.choose(ctx, query.copy(section = section))
close()
}
}
}
BrowseDropdown(priceLabel(query.price)) { first, close ->
GameJoltBrowse.prices.forEachIndexed { index, price ->
MenuItem(priceLabel(price), query.price == price, focusRequester = if (index == 0) first else null) {
GameJoltBrowseState.choose(ctx, query.copy(price = price))
close()
}
}
}
val anyPlatform = stringResource(R.string.stores_itch_platform_any)
BrowseDropdown(browseSummary(GameJoltBrowse.systems.filter { it in query.os }.map { systemLabel(it) }, anyPlatform)) { first, _ ->
MenuItem(anyPlatform, query.os.isEmpty(), focusRequester = first) { GameJoltBrowseState.choose(ctx, query.copy(os = emptySet())) }
for (os in GameJoltBrowse.systems) MenuItem(systemLabel(os), os in query.os) { GameJoltBrowseState.choose(ctx, query.copy(os = toggle(query.os, os))) }
}
BrowseDropdown(browseSummary(GameJoltBrowse.browsers.filter { it in query.browser }.map { browserLabel(it) }, stringResource(R.string.stores_gamejolt_filter_browser))) { first, _ ->
GameJoltBrowse.browsers.forEachIndexed { index, browser ->
MenuItem(browserLabel(browser), browser in query.browser, focusRequester = if (index == 0) first else null) { GameJoltBrowseState.choose(ctx, query.copy(browser = toggle(query.browser, browser))) }
}
}
val maturities = GameJoltBrowse.maturities.filter { showMature || it != "adult" }
BrowseDropdown(browseSummary(maturities.filter { it in query.maturity }.map { maturityLabel(it) }, stringResource(R.string.stores_gamejolt_filter_maturity))) { first, _ ->
maturities.forEachIndexed { index, maturity ->
MenuItem(maturityLabel(maturity), maturity in query.maturity, focusRequester = if (index == 0) first else null) { GameJoltBrowseState.choose(ctx, query.copy(maturity = toggle(query.maturity, maturity))) }
}
}
BrowseDropdown(browseSummary(GameJoltBrowse.statuses.filter { it in query.status }.map { statusLabel(it) }, stringResource(R.string.stores_gamejolt_filter_status))) { first, _ ->
GameJoltBrowse.statuses.forEachIndexed { index, status ->
MenuItem(statusLabel(status), status in query.status, focusRequester = if (index == 0) first else null) { GameJoltBrowseState.choose(ctx, query.copy(status = toggle(query.status, status))) }
}
}
val partners = stringResource(R.string.stores_gamejolt_partners)
BrowseDropdown(if (query.partners) partners else stringResource(R.string.stores_gamejolt_filter_partners)) { first, _ ->
MenuItem(partners, query.partners, focusRequester = first) { GameJoltBrowseState.choose(ctx, query.copy(partners = !query.partners)) }
}
}
ChipRow {
for (tag in query.tags) BrowseChip("$tag ✕", true) { GameJoltBrowseState.choose(ctx, query.copy(tags = query.tags - tag)) }
BrowseChip(stringResource(R.string.stores_itch_tag_add), false) { picking = true }
}
}
if (picking) TextEntryDialog(
stringResource(R.string.stores_itch_tag_title), "", number = false, confirm = stringResource(R.string.common_ok),
onSubmit = { value -> GameJoltBrowse.tagSlug(value).takeIf { it.isNotEmpty() }?.let { GameJoltBrowseState.choose(ctx, query.copy(tags = (query.tags + it).distinct())) } },
onDismiss = { picking = false }, id = "gamejolt-tag",
)
}
@Composable
internal fun GameJoltLoadMore() {
val ctx = LocalContext.current
val count = GameJoltBrowseState.items.size
LaunchedEffect(Unit) { GameJoltBrowseState.more(ctx) }
if (GameJoltBrowseState.loading) LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 12.dp))
else if (GameJoltBrowseState.failed) Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
BrowseChip(stringResource(R.string.stores_dl_retry), false) { GameJoltBrowseState.more(ctx, retry = true) }
}
else if (!GameJoltBrowseState.ended && count > 0) Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
BrowseChip(stringResource(R.string.stores_itch_load_more), false) { GameJoltBrowseState.more(ctx) }
}
}
@Composable
private fun sectionLabel(section: String): String = stringResource(
when (section) {
GameJoltBrowse.SECTION_HOT -> R.string.stores_gamejolt_section_hot
GameJoltBrowse.SECTION_BEST -> R.string.stores_gamejolt_section_best
GameJoltBrowse.SECTION_NEW -> R.string.stores_gamejolt_section_new
else -> R.string.stores_gamejolt_section_featured
},
)
@Composable
private fun priceLabel(price: String): String = stringResource(
when (price) {
GameJoltBrowse.PRICE_FREE -> R.string.stores_itch_price_free
GameJoltBrowse.PRICE_SALE -> R.string.stores_itch_price_sale
GameJoltBrowse.PRICE_PAID -> R.string.stores_itch_price_paid
GameJoltBrowse.PRICE_UNDER_5 -> R.string.stores_itch_price_under_5
GameJoltBrowse.PRICE_UNDER_15 -> R.string.stores_itch_price_under_15
GameJoltBrowse.PRICE_UNDER_30 -> R.string.stores_gamejolt_price_under_30
else -> R.string.stores_itch_price_any
},
)
@Composable
private fun systemLabel(os: String): String = stringResource(
when (os) {
"windows" -> R.string.stores_itch_platform_windows
"mac" -> R.string.stores_itch_platform_macos
"linux" -> R.string.stores_itch_platform_linux
else -> R.string.stores_gamejolt_os_other
},
)
@Composable
private fun browserLabel(browser: String): String = when (browser) {
"html" -> "HTML"
"flash" -> "Flash"
else -> "Unity"
}
@Composable
private fun maturityLabel(maturity: String): String = stringResource(
when (maturity) {
"everyone" -> R.string.stores_gamejolt_maturity_everyone
"teen" -> R.string.stores_gamejolt_maturity_teen
else -> R.string.stores_gamejolt_maturity_adult
},
)
@Composable
private fun statusLabel(status: String): String = stringResource(
when (status) {
"complete" -> R.string.stores_gamejolt_status_complete
else -> R.string.stores_gamejolt_status_early
},
)
@@ -0,0 +1,129 @@
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.getValue
import androidx.compose.runtime.key
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.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.gamejolt.GameJoltApi
import com.droiddeck.launcher.stores.gamejolt.GameJoltBuild
import com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
private const val CHOOSE = "choose"
@Composable
internal fun GameJoltVersionButton(installed: InstalledStoreGame, enabled: Boolean) {
SecondaryButton(stringResource(R.string.stores_itch_pick_title), enabled = enabled) {
val sidecar = installed.sidecar
val paid = sidecar.extra["paid"] == "1"
StoresState.gameJoltPicking = CatalogItem(
store = Store.GAMEJOLT, id = sidecar.id, title = sidecar.title, imageUrl = sidecar.cover, isFree = !paid,
storeUrl = GameJoltApi.pageUrl("game", sidecar.id),
extra = mapOf("gameId" to (sidecar.extra["gameId"] ?: sidecar.id), CHOOSE to "1"),
)
}
}
@Composable
internal fun GameJoltBuildPicker(requested: CatalogItem, onDismiss: () -> Unit) {
val item = requested.copy(owned = requested.owned || StoresState.library[Store.GAMEJOLT].orEmpty().any { it.id == requested.id && it.owned })
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(requested) { mutableStateOf<List<GameJoltBuild>?>(null) }
var failed by remember(requested) { mutableStateOf(false) }
val install: (GameJoltBuild) -> Unit = install@{ build ->
if (!shown.targetState) return@install
val tagged = item.copy(
extra = item.extra + mapOf("buildId" to build.id),
sizeBytes = build.size.takeIf { it > 0 } ?: item.sizeBytes,
)
close()
StoresState.requestInstall(ctx, tagged)
}
LaunchedEffect(requested) {
val gameId = item.extra["gameId"].orEmpty().ifEmpty { item.id }
val result = withContext(Dispatchers.IO) { GameJoltBuilds.load(app, gameId) }
if (result == null) { failed = true; return@LaunchedEffect }
loaded = result
if ((item.isFree || item.owned) && item.extra[CHOOSE] != "1" && shown.targetState) result.singleOrNull()?.takeIf { it.installable }?.let { install(it) }
}
AppDialog(shown, close, "gameJoltBuilds", 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_gamejolt_pick_failed), fontSize = 13.sp, color = colors.onSurfaceVariant)
list == null -> LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 8.dp))
list.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) key(build.id) { BuildRow(item, build) { install(build) } }
}
}
}
}
@Composable
private fun BuildRow(item: CatalogItem, build: GameJoltBuild, onInstall: () -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val linux = "linux" in build.platforms && !build.installable
val canInstall = build.installable && (item.isFree || item.owned)
val names = build.platforms.map { platformName(it) }
val detail = listOfNotNull(
names.joinToString(", "),
build.size.takeIf { it > 0 }?.let { formatBytes(it) },
build.version.takeIf { it.isNotBlank() },
).joinToString(" · ")
ListRow(enabled = !linux, onClick = { if (canInstall) onInstall() else openStoreUrl(ctx, item) }) {
Column(Modifier.weight(1f)) {
Text(build.filename.ifBlank { build.packageTitle.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 {
canInstall -> stringResource(R.string.stores_install)
linux -> stringResource(R.string.stores_itch_build_linux_soon)
else -> stringResource(R.string.stores_gamejolt_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
"other" -> R.string.stores_gamejolt_os_other
else -> R.string.stores_itch_build_web
},
)
@@ -0,0 +1,61 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.gamejolt.GameJoltUpdate
import com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates
@Composable
internal fun GameJoltCheckButton(installed: InstalledStoreGame) {
val ctx = LocalContext.current
IconAction(Icons.Filled.Refresh, stringResource(R.string.store_check_updates), "game:check-updates", enabled = GameJoltUpdates.checkingKey == null, frosted = true) {
GameJoltUpdates.checkGame(ctx, installed)
}
}
@Composable
internal fun GameJoltUpdateButton(installed: InstalledStoreGame, enabled: Boolean) {
val ctx = LocalContext.current
val update = GameJoltUpdates.available[installed.key] ?: return
var asking by remember { mutableStateOf(false) }
SecondaryButton(stringResource(R.string.common_update), enabled = enabled) {
if (update.replaced) asking = true else GameJoltUpdates.start(ctx, installed, update)
}
if (asking) GameJoltReplacedDialog(installed, update) { asking = false }
}
@Composable
private fun GameJoltReplacedDialog(installed: InstalledStoreGame, update: GameJoltUpdate, onDismiss: () -> Unit) {
val ctx = LocalContext.current
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
AppDialog(shown, close, "gameJoltUpdate", wide = false, maxWidth = 460.dp) {
DialogTitleRow(installed.sidecar.title, close)
Text(
stringResource(R.string.stores_itch_update_replaced, update.filename.ifBlank { update.buildId }),
fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
PrimaryButton(stringResource(R.string.common_update)) {
close()
GameJoltUpdates.start(ctx, installed, update)
}
SecondaryButton(stringResource(R.string.common_cancel)) { close() }
}
}
}
@@ -8,6 +8,7 @@ import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
@@ -19,6 +20,7 @@ import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -27,6 +29,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
@@ -44,16 +47,29 @@ internal fun ItchBrowseBar() {
var picking by remember { mutableStateOf(false) }
Column(Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
ChipRow {
for (sort in ItchBrowse.sorts) BrowseChip(sortLabel(sort), query.sort == sort) { ItchBrowseState.choose(ctx, query.copy(sort = sort)) }
}
ChipRow {
for (price in ItchBrowse.prices) BrowseChip(priceLabel(price), query.price == price) { ItchBrowseState.choose(ctx, query.copy(price = price)) }
}
ChipRow {
BrowseChip(stringResource(R.string.stores_itch_platform_any), query.platforms.isEmpty()) { ItchBrowseState.choose(ctx, query.copy(platforms = emptySet())) }
for (platform in ItchBrowse.platformNames) {
val on = platform in query.platforms
BrowseChip(platformLabel(platform), on) { ItchBrowseState.choose(ctx, query.copy(platforms = if (on) query.platforms - platform else query.platforms + platform)) }
BrowseDropdown(sortLabel(query.sort)) { first, close ->
ItchBrowse.sorts.forEachIndexed { index, sort ->
MenuItem(sortLabel(sort), query.sort == sort, focusRequester = if (index == 0) first else null) {
ItchBrowseState.choose(ctx, query.copy(sort = sort))
close()
}
}
}
BrowseDropdown(priceLabel(query.price)) { first, close ->
ItchBrowse.prices.forEachIndexed { index, price ->
MenuItem(priceLabel(price), query.price == price, focusRequester = if (index == 0) first else null) {
ItchBrowseState.choose(ctx, query.copy(price = price))
close()
}
}
}
val anyPlatform = stringResource(R.string.stores_itch_platform_any)
BrowseDropdown(browseSummary(ItchBrowse.platformNames.filter { it in query.platforms }.map { platformLabel(it) }, anyPlatform)) { first, _ ->
MenuItem(anyPlatform, query.platforms.isEmpty(), focusRequester = first) { ItchBrowseState.choose(ctx, query.copy(platforms = emptySet())) }
for (platform in ItchBrowse.platformNames) {
val on = platform in query.platforms
MenuItem(platformLabel(platform), on) { ItchBrowseState.choose(ctx, query.copy(platforms = if (on) query.platforms - platform else query.platforms + platform)) }
}
}
}
ChipRow {
@@ -83,7 +99,7 @@ internal fun ItchLoadMore() {
}
@Composable
private fun ChipRow(content: @Composable () -> Unit) {
internal fun ChipRow(content: @Composable () -> Unit) {
Row(
horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).selectableGroup(),
@@ -91,7 +107,22 @@ private fun ChipRow(content: @Composable () -> Unit) {
}
@Composable
private fun BrowseChip(label: String, selected: Boolean, onClick: () -> Unit) {
internal fun BrowseDropdown(text: String, content: @Composable ColumnScope.(FocusRequester, () -> Unit) -> Unit) {
var expanded by remember { mutableStateOf(false) }
Box {
CompositionLocalProvider(LocalChipMinWidth provides 0.dp) { ValueChip(text, expanded) { expanded = !expanded } }
AnchoredMenu(expanded, onDismiss = { expanded = false }, compact = true, minWidth = 160.dp) { first -> content(first) { expanded = false } }
}
}
internal fun browseSummary(labels: List<String>, empty: String): String = when (labels.size) {
0 -> empty
1, 2 -> labels.joinToString(", ")
else -> "${labels.first()} +${labels.size - 1}"
}
@Composable
internal fun BrowseChip(label: String, selected: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(8.dp)
@@ -102,7 +102,8 @@ import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.itch.ItchCollection
import com.droiddeck.launcher.stores.gamejolt.GameJoltCollections
import com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates
import com.droiddeck.launcher.stores.itch.ItchCollections
import com.droiddeck.launcher.stores.itch.ItchUpdates
import com.droiddeck.launcher.stores.gog.GogMaintenance
@@ -142,20 +143,20 @@ internal fun libraryEntries(
return out.distinctBy { it.key }
}
internal fun collectionEntries(all: List<LibraryEntry>, items: List<CatalogItem>): List<LibraryEntry> {
internal fun collectionEntries(all: List<LibraryEntry>, items: List<CatalogItem>, store: Store = Store.ITCH): List<LibraryEntry> {
val keys = items.map { it.key }.toSet()
val itch = all.filter { it.source == Store.ITCH.id }
val have = itch.mapNotNull { it.storeKey }.toSet()
return itch.filter { it.storeKey in keys } +
items.filter { it.key !in have }.map { LibraryEntry(GameRef.key(it), Store.ITCH.id, it.title, null, it, false) }
val own = all.filter { it.source == store.id }
val have = own.mapNotNull { it.storeKey }.toSet()
return own.filter { it.storeKey in keys } +
items.filter { it.key !in have }.map { LibraryEntry(GameRef.key(it), store.id, it.title, null, it, false) }
}
internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = entries.partition { it.installed }.let { (on, off) -> on + off }
internal const val LIBRARY_ALL = "all"
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>): List<String> =
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>, always: Set<String> = emptySet()): List<String> =
(listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED)
.filter { source -> entries.any { it.source == source } }
.filter { source -> source in always || entries.any { it.source == source } }
internal object LibraryDisplay {
val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f)
@@ -225,7 +226,11 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
var showUninstalled by remember(LibraryView.ownedRequest) { mutableStateOf(SessionPrefs.libraryShowUninstalled(ctx)) }
var collectionShows by remember { mutableStateOf<Pair<String, Boolean>?>(null) }
val setShowUninstalled = { show: Boolean ->
val picked = ItchCollections.selected.takeIf { LibraryView.source == Store.ITCH.id }
val picked = when (LibraryView.source) {
Store.ITCH.id -> ItchCollections.selected
Store.GAMEJOLT.id -> GameJoltCollections.selected
else -> null
}
if (picked != null) collectionShows = picked to show
else {
showUninstalled = show
@@ -233,21 +238,32 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
}
}
val itchSignedIn = owned.containsKey(Store.ITCH)
val listed = librarySources(all, SessionPrefs.storesTabOrder(ctx))
val sources = if (itchSignedIn && Store.ITCH.id !in listed) listed + Store.ITCH.id else listed
val gameJoltSignedIn = owned.containsKey(Store.GAMEJOLT)
val sources = librarySources(all, SessionPrefs.storesTabOrder(ctx), listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn }).toSet())
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
val q = LibraryView.query.trim().lowercase()
val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL
LaunchedEffect(source, itchSignedIn) { if (source == Store.ITCH.id && itchSignedIn) {
ItchCollections.load(ctx)
ItchUpdates.check(ctx)
} }
val collection = if (source == Store.ITCH.id) ItchCollections.chosen() else null
val pool = if (collection == null) all else collectionEntries(all, ItchCollections.gamesOf(collection.id).orEmpty())
LaunchedEffect(source, itchSignedIn, gameJoltSignedIn) {
if (source == Store.ITCH.id && itchSignedIn) {
ItchCollections.load(ctx)
ItchUpdates.check(ctx)
}
if (source == Store.GAMEJOLT.id && gameJoltSignedIn) {
GameJoltCollections.load(ctx)
GameJoltUpdates.check(ctx)
}
}
val collectionId = when (source) {
Store.ITCH.id -> ItchCollections.chosen()?.id
Store.GAMEJOLT.id -> GameJoltCollections.chosen()?.id
else -> null
}
val collectionItems = collectionId?.let { if (source == Store.GAMEJOLT.id) GameJoltCollections.gamesOf(it) else ItchCollections.gamesOf(it) }
val pool = if (collectionId == null) all else collectionEntries(all, collectionItems.orEmpty(), Store.byId(source) ?: Store.ITCH)
val matching = pool.filter {
(source == LIBRARY_ALL || it.source == source) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
}
val listUninstalled = if (collection == null) showUninstalled else collectionShows?.takeIf { it.first == collection.id }?.second ?: true
val listUninstalled = if (collectionId == null) showUninstalled else collectionShows?.takeIf { it.first == collectionId }?.second ?: true
val candidates = if (listUninstalled) matching else matching.filter { it.installed }
val hiddenUninstalled = if (listUninstalled) 0 else matching.count { !it.installed }
val sort = s.storesSort
@@ -332,7 +348,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
kotlinx.coroutines.delay(Motion.ms(240).toLong())
focusWithinFrames({ ff.last?.startsWith("card:") == true }) { if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
}
if (all.isEmpty() && open == null && !itchSignedIn) {
if (all.isEmpty() && open == null && !itchSignedIn && !gameJoltSignedIn) {
LibraryEmpty(s, a, modifier)
return
}
@@ -453,7 +469,7 @@ private fun LibraryGrid(
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
) {
item(key = "header", span = { GridItemSpan(maxLineSpan) }) {
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = source == Store.ITCH.id) }
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }) }
}
item(key = "filters", span = { GridItemSpan(maxLineSpan) }) {
Rise(1) { LibraryFilters(sources, source, onSource) }
@@ -514,7 +530,7 @@ private fun LazyGridScope.libraryGrid(entries: List<LibraryEntry>, empty: Int, t
@Composable
private fun LibraryHeader(
s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean,
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Boolean,
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Store?,
) {
val colors = MaterialTheme.colorScheme
val narrow = LocalNarrowPane.current
@@ -532,7 +548,7 @@ private fun LibraryHeader(
) {
DisplayButton()
if (showUninstalled != null || xbox) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox)
if (collections) CollectionsButton()
if (collections != null) CollectionsButton(collections)
SortButton(s, a)
ViewButton(s, a)
GameFileFolderActions(s, a)
@@ -725,7 +741,7 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?, showDownlo
}
}
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available } == true ||
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available || it in GameJoltUpdates.available } == true ||
e.source == Store.GOG.id && (e.item?.id ?: e.game?.storeId)?.let { GogMaintenance.checks[it]?.state } == GogMaintenance.State.AVAILABLE
@Composable
@@ -863,16 +879,21 @@ private fun LibraryFilterButton(showUninstalled: Boolean?, onShowUninstalled: (B
}
@Composable
private fun CollectionsButton() {
private fun CollectionsButton(store: Store) {
val pal = LocalPalette.current
val ctx = LocalContext.current
val title = stringResource(R.string.itch_collections)
val all = stringResource(R.string.stores_tab_all)
var at by remember { mutableStateOf<Rect?>(null) }
val gameJolt = store == Store.GAMEJOLT
val chosenTitle = if (gameJolt) GameJoltCollections.chosen()?.title else ItchCollections.chosen()?.title
val selectedId = if (gameJolt) GameJoltCollections.selected else ItchCollections.selected
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
HeaderIconButton(title + " · " + (ItchCollections.chosen()?.title ?: all), CollectionsIcon, "itch-collections") {
HeaderIconButton(title + " · " + (chosenTitle ?: all), CollectionsIcon, "${store.id}-collections") {
val from = at ?: return@HeaderIconButton
val choices = listOf<ItchCollection?>(null) + ItchCollections.list
val choices = listOf<Pair<String, String>?>(null) + if (gameJolt) GameJoltCollections.list.map { c ->
c.id to (c.title + (GameJoltCollections.gamesOf(c.id)?.let { " (" + it.size + ")" }.orEmpty()))
} else ItchCollections.list.map { c -> c.id to (c.title + " (" + c.count + ")") }
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = choices.size,
handle = { Icon(CollectionsIcon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
@@ -880,12 +901,12 @@ private fun CollectionsButton() {
StepTitle(title)
StepList {
choices.forEachIndexed { i, c ->
val picked = c?.id == ItchCollections.selected
val picked = c?.first == selectedId
StepChoice(
c?.let { it.title + " (" + it.count + ")" } ?: all, selected = picked, enabled = open,
c?.second ?: all, selected = picked, enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (picked) Modifier.focusRequester(first) else Modifier),
) {
ItchCollections.select(ctx, c?.id)
if (gameJolt) GameJoltCollections.select(ctx, c?.first) else ItchCollections.select(ctx, c?.first)
Steps.fold()
}
}
@@ -26,6 +26,7 @@ import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.size
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.foundation.shape.CircleShape
@@ -371,11 +372,12 @@ fun MenuItem(
.background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent)
.glideBorder(hot && enabled, RoundedCornerShape(8.dp), pal.signal)
.alpha(if (enabled) 1f else 0.4f)
.semantics { selected = checked }
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 10.dp, vertical = 9.dp),
) {
Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f))
Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f).clearAndSetSemantics {})
if (leading != null) {
leading()
Spacer(Modifier.width(8.dp))
@@ -31,6 +31,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
Store.AMAZON.id -> SourceColours(Color(0xFF3A2A0A), Color(0xFFFFC266), Color(0xFFFF9900))
Store.XBOX.id -> SourceColours(Color(0xFF17381B), Color(0xFFC6EDC2), Color(0xFF70C850))
Store.ITCH.id -> SourceColours(Color(0xFF3A1A1E), Color(0xFFFFB3B3), Color(0xFFFF5C5C))
Store.GAMEJOLT.id -> SourceColours(Color(0xFF232E00), Color(0xFFE3FF66), Color(0xFFCCFF00))
Store.BATTLENET.id -> SourceColours(Color(0xFF0A2440), Color(0xFF9DD1FF), Color(0xFF148EFF))
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
@@ -45,6 +46,7 @@ internal fun sourceLabel(source: String): String = when (source) {
Store.AMAZON.id -> Store.AMAZON.label
Store.XBOX.id -> Store.XBOX.label
Store.ITCH.id -> Store.ITCH.label
Store.GAMEJOLT.id -> Store.GAMEJOLT.label
Store.BATTLENET.id -> Store.BATTLENET.label
else -> stringResource(R.string.source_added)
}
@@ -130,6 +130,7 @@ import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.gamejolt.GameJoltBrowseState
import com.droiddeck.launcher.stores.itch.ItchBrowseState
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreTab
@@ -389,7 +390,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
}
}
},
) { key -> GameDetail(key, s, a, heroFocus, backLabel, hopRail = null, onBack = { closeGame() }) }
) { key -> GameDetail(key, s, a, heroFocus, backLabel, hopRail = null, onBack = { closeGame() }, inStore = true) }
}
FlightLayer(hostAt)
StoresMotion.step?.let { ask ->
@@ -827,8 +828,10 @@ private fun Storefront(
fun shown(i: CatalogItem) = s.storesShowMature || !i.mature || i.accessible
fun shelf(l: List<CatalogItem>?) = l?.filter(::shown)
LaunchedEffect(store, q) { StoresState.search(ctx, store, q) }
val browsing = store == Store.ITCH && q.isEmpty() && ItchBrowseState.active
val browseItems = if (browsing) ItchBrowseState.items else emptyList()
val gameJolt = store == Store.GAMEJOLT
LaunchedEffect(gameJolt, s.storesShowMature) { if (gameJolt) GameJoltBrowseState.sync(ctx, s.storesShowMature) }
val browsing = q.isEmpty() && ((store == Store.ITCH && ItchBrowseState.active) || gameJolt)
val browseItems = if (!browsing) emptyList() else if (gameJolt) GameJoltBrowseState.items else ItchBrowseState.items
val catalog = store == Store.BATTLENET && q.isEmpty()
val visible = remember(found, library, shelves, q, s.storesShowMature, browsing, browseItems, catalog) {
if (catalog) shelf(shelves?.trending) ?: emptyList()
@@ -840,8 +843,10 @@ private fun Storefront(
.filter { (it.title.lowercase().contains(q) || it.key in foundKeys) && shown(it) }
}
val nothing = stringResource(when {
browsing && ItchBrowseState.loading -> R.string.stores_shelves_loading
browsing && ItchBrowseState.failed -> R.string.stores_itch_browse_failed
browsing && gameJolt && GameJoltBrowseState.loading -> R.string.stores_shelves_loading
browsing && gameJolt && GameJoltBrowseState.failed -> R.string.stores_gamejolt_browse_failed
browsing && !gameJolt && ItchBrowseState.loading -> R.string.stores_shelves_loading
browsing && !gameJolt && ItchBrowseState.failed -> R.string.stores_itch_browse_failed
catalog && shelves == null -> R.string.stores_shelves_loading
else -> R.string.stores_nothing_matches
})
@@ -857,7 +862,8 @@ private fun Storefront(
val bareTab = if (searching) visible.isEmpty() else shelves == null || shelves.isEmpty
val barLine = StoresState.status[store]?.takeIf { bareTab && syncCount(it) != null }
val itchBar = store == Store.ITCH && q.isEmpty()
val headerItems = 2 + (if (barLine != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0) + (if (itchBar) 1 else 0) + (if (catalog) 1 else 0)
val gameJoltBar = gameJolt && q.isEmpty()
val headerItems = 2 + (if (barLine != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0) + (if (itchBar || gameJoltBar) 1 else 0) + (if (catalog) 1 else 0)
val card: @Composable (CatalogItem) -> Unit = { item ->
val first = if (searching) item.key == visible.firstOrNull()?.key else !firstPlaced
firstPlaced = true
@@ -906,12 +912,14 @@ private fun Storefront(
barLine?.let { line -> item(key = "sync", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { SyncBar(line) } } }
StoresState.problems[store]?.let { line -> item(key = "problem", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { Box(Modifier.padding(bottom = 8.dp)) { Note(line) } } } }
if (itchBar) item(key = "itch-browse-bar", span = { GridItemSpan(maxLineSpan) }) { ItchBrowseBar() }
if (gameJoltBar) item(key = "gamejolt-browse-bar", span = { GridItemSpan(maxLineSpan) }) { GameJoltBrowseBar(s.storesShowMature) }
if (catalog) item(key = "catalog-label", span = { GridItemSpan(maxLineSpan) }) {
Box(Modifier.padding(top = 10.dp)) { SectionLabel(stringResource(R.string.bnet_store)) }
}
if (searching) {
storeGrid(visible, nothing, card)
if (browsing) item(key = "itch-more", span = { GridItemSpan(maxLineSpan) }) { ItchLoadMore() }
if (browsing && gameJolt) item(key = "gamejolt-more", span = { GridItemSpan(maxLineSpan) }) { GameJoltLoadMore() }
else if (browsing) item(key = "itch-more", span = { GridItemSpan(maxLineSpan) }) { ItchLoadMore() }
} else item(key = "shelves", span = { GridItemSpan(maxLineSpan) }) {
Column {
Shelf(stringResource(R.string.stores_shelf_new), shelf(shelves?.whatsNew), card)
@@ -1147,6 +1155,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
Store.AMAZON -> Color(0xFFFF9900) to Color(0xFFE07800)
Store.XBOX -> Color(0xFF70C850) to Color(0xFF107C10)
Store.ITCH -> Color(0xFFFF5C5C) to Color(0xFFD93B3B)
Store.GAMEJOLT -> Color(0xFFCCFF00) to Color(0xFFA3CC00)
Store.BATTLENET -> Color(0xFF148EFF) to Color(0xFF0B6BD3)
null -> return base
}