diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 01657d289c..0d099cbf0b 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt index ace3304159..2af7a9bff4 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt @@ -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? { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt index 79ca0f8492..4e53c5ea08 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/Store.kt b/app/src/main/java/com/droiddeck/launcher/stores/Store.kt index 54476b6e19..b7d0fbce1c 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/Store.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/Store.kt @@ -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 } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreArchiveUnpacker.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreArchiveUnpacker.kt new file mode 100644 index 0000000000..ef355cc038 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreArchiveUnpacker.kt @@ -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, 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() + 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) + } + } + } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt index 6814ad4e95..2ba84041f8 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt @@ -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 = roots(context).flatMap { root -> Store.entries.flatMap { store -> diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt index 91d96f6ec5..228d97cd78 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt @@ -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) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt index 290676c9ed..545c981e50 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt @@ -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) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index 2902cd3664..f28c402e8e 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -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(null) var itchPicking by mutableStateOf(null) + var gameJoltPicking by mutableStateOf(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) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltApi.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltApi.kt new file mode 100644 index 0000000000..fce0696a15 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltApi.kt @@ -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() } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltAuth.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltAuth.kt new file mode 100644 index 0000000000..1cc9f05758 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltAuth.kt @@ -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) +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBackend.kt new file mode 100644 index 0000000000..09444f42a8 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBackend.kt @@ -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 { + val cookies = GameJoltAuth.cookies(context) + val items = ArrayList() + 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) {} +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBrowse.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBrowse.kt new file mode 100644 index 0000000000..4aa8df90da --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBrowse.kt @@ -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 = emptySet(), + val browser: Set = emptySet(), + val maturity: Set = emptySet(), + val status: Set = emptySet(), + val partners: Boolean = false, + val tags: List = 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() + 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, val code: Int, val rawIds: List) + + 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>(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() + + 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() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBuilds.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBuilds.kt new file mode 100644 index 0000000000..a014e7d6ec --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBuilds.kt @@ -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, + val folder: String, + val executable: String, +) { + val installable: Boolean get() = "windows" in platforms +} + +internal object GameJoltBuilds { + fun parse(payload: JSONObject?): List { + 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 { it.installable }.thenByDescending { it.stamp.toLongOrNull() ?: 0L }.thenByDescending { it.id.toLongOrNull() ?: 0L }) + } + + fun platforms(build: JSONObject): Set { + val found = LinkedHashSet() + 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? { + val answer = GameJoltApi.overview(gameId, GameJoltAuth.cookies(context)) + if (!answer.ok) return null + return parse(answer.payload) + } + + fun byId(builds: List, id: String): GameJoltBuild? = builds.firstOrNull { it.id == id } + + fun preferred(builds: List): 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 = + if (array == null) emptyList() else (0 until array.length()).mapNotNull { array.optJSONObject(it) } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltCatalog.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltCatalog.kt new file mode 100644 index 0000000000..5303d65b47 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltCatalog.kt @@ -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 { + 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)) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltCollections.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltCollections.kt new file mode 100644 index 0000000000..887a071acb --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltCollections.kt @@ -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>(emptyList()) + private set + var selected by mutableStateOf(null) + private set + private val games = mutableStateMapOf>() + private val loading = ConcurrentHashMap.newKeySet() + @Volatile private var generation = 0 + + fun items(): List = games.values.flatten() + + fun gamesOf(id: String): List? = 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 = (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) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltInstaller.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltInstaller.kt new file mode 100644 index 0000000000..c6653bf9be --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltInstaller.kt @@ -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) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltLibrary.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltLibrary.kt new file mode 100644 index 0000000000..e5f69d4f19 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltLibrary.kt @@ -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? { + val cookies = GameJoltAuth.cookies(context) + val out = ArrayList() + val seen = HashSet() + 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 + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltLogin.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltLogin.kt new file mode 100644 index 0000000000..e8a547ed2b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltLogin.kt @@ -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") + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltPrefs.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltPrefs.kt new file mode 100644 index 0000000000..3790e3ea6a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltPrefs.kt @@ -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) +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltPricing.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltPricing.kt new file mode 100644 index 0000000000..2986f0f7c4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltPricing.kt @@ -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" + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltUpdates.kt b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltUpdates.kt new file mode 100644 index 0000000000..9b8b6a3642 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/gamejolt/GameJoltUpdates.kt @@ -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() + var checkingKey by mutableStateOf(null) + private set + + private val running = AtomicBoolean(false) + private val restored = AtomicBoolean(false) + @Volatile private var generation = 0 + + internal fun evaluate(builds: List?, 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 = 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 { + val json = runCatching { JSONObject(raw.orEmpty()) }.getOrNull() ?: return emptyMap() + val out = LinkedHashMap() + 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 = + 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() + val answered = HashSet() + val seen = HashMap>() + 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() } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchInstaller.kt b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchInstaller.kt index 3896091e3d..79b2725f1c 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchInstaller.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchInstaller.kt @@ -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, 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() - 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 } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index f40d82d391..eff9453d6a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -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 -> diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index f2f7d5ee93..f7efc043ff 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -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) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameJoltBrowseBar.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameJoltBrowseBar.kt new file mode 100644 index 0000000000..96057ea1d7 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameJoltBrowseBar.kt @@ -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, value: String): Set = 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 + }, +) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameJoltBuildPicker.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameJoltBuildPicker.kt new file mode 100644 index 0000000000..7e5f06600a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameJoltBuildPicker.kt @@ -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?>(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 + }, +) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameJoltUpdateButton.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameJoltUpdateButton.kt new file mode 100644 index 0000000000..c351495142 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameJoltUpdateButton.kt @@ -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() } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ItchBrowseBar.kt b/app/src/main/java/com/droiddeck/launcher/ui/ItchBrowseBar.kt index 276d131fee..fe65d598f4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ItchBrowseBar.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ItchBrowseBar.kt @@ -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, 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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index 482aeb5a63..6550a2fd06 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -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, items: List): List { +internal fun collectionEntries(all: List, items: List, store: Store = Store.ITCH): List { 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): List = entries.partition { it.installed }.let { (on, off) -> on + off } internal const val LIBRARY_ALL = "all" -internal fun librarySources(entries: List, order: List): List = +internal fun librarySources(entries: List, order: List, always: Set = emptySet()): List = (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?>(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, 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(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(null) + ItchCollections.list + val choices = listOf?>(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() } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index b389992cf6..df74bb5850 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -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)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt index 40bfd22c4c..1d2aef9d6e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt @@ -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) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 35c21173eb..f9e2ed798f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -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?) = 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 } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 98e2321e68..8ef0684fde 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -3754,4 +3754,33 @@ إصلاح الملفات تحديث التثبيت اختيار + ليس في مكتبة Game Jolt الخاصة بك + لا يوجد تنزيل لنظام Windows لهذه اللعبة + لم يتم العثور على لعبة Windows في التنزيل + تعذر العثور على هذه اللعبة على Game Jolt + تعذّر تحميل الألعاب من Game Jolt + استجاب Game Jolt بـ HTTP %1$d + تعذر تحميل التنزيلات من Game Jolt + فتح على Game Jolt + أرشيفات %1$s غير مدعومة + تعذر استخراج التنزيل (رمز الخروج %1$d) + تعذر الوصول إلى Game Jolt + لم يوفر Game Jolt رابط تنزيل + مميزة + رائجة + الأفضل + جديدة + 30$ أو أقل + أخرى + لجميع الأعمار + المراهقون + للبالغين + مكتملة + وصول مبكر + ألعاب الشركاء + المتصفح + التصنيف العمري + الحالة + الشركاء + الألعاب المتابَعة diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 5a31def7b6..9cd7421dcc 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -3616,4 +3616,33 @@ Reparar archivos Renovar la instalación Seleccionar + No está en tu biblioteca de Game Jolt + Este juego no tiene descarga para Windows + No se encontró un juego de Windows en la descarga + No se encontró este juego en Game Jolt + No se pudieron cargar los juegos de Game Jolt + Game Jolt respondió HTTP %1$d + No se pudieron cargar las descargas de Game Jolt + Abrir en Game Jolt + Los archivos %1$s no son compatibles + No se pudo extraer la descarga (salida %1$d) + No se pudo conectar con Game Jolt + Game Jolt no entregó un enlace de descarga + Destacados + Populares + Mejores + Nuevos + $30 o menos + Otros + Todas las edades + Adolescentes + Maduro + Completo + Acceso anticipado + Juegos de socios + Navegador + Clasificación + Estado + Socios + Juegos seguidos diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 4bca78ed5d..a8e1c9f743 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -3606,4 +3606,33 @@ Поправка на файловете Обновяване на инсталацията Избор + Не е в библиотеката ви в Game Jolt + Няма изтегляне за Windows за тази игра + В изтеглянето не е намерена игра за Windows + Играта не беше намерена в Game Jolt + Игрите от Game Jolt не можаха да се заредят + Game Jolt отговори HTTP %1$d + Изтеглянията от Game Jolt не можаха да се заредят + Отваряне в Game Jolt + Архивите %1$s не се поддържат + Изтеглянето не можа да бъде разархивирано (код %1$d) + Game Jolt не може да бъде достигнат + Game Jolt не даде връзка за изтегляне + Препоръчани + Популярни + Най-добри + Нови + $30 или по-малко + Други + За всички възрасти + Тийнейджъри + За възрастни + Завършени + Ранен достъп + Игри на партньори + Браузър + Зрялост + Статус + Партньори + Следвани игри diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 3a479c7551..b8b3382b2b 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -3680,4 +3680,33 @@ Opravit soubory Obnovit instalaci Vybrat + Není ve vaší knihovně Game Jolt + Pro tuto hru není ke stažení verze pro Windows + Ve stahování nebyla nalezena hra pro Windows + Tuto hru se na Game Jolt nepodařilo najít + Hry z Game Jolt se nepodařilo načíst + Game Jolt odpovědělo HTTP %1$d + Stahování z Game Jolt se nepodařilo načíst + Otevřít na Game Jolt + Archivy %1$s nejsou podporovány + Stažený soubor nelze rozbalit (kód %1$d) + Game Jolt není dostupný + Game Jolt neposkytl odkaz ke stažení + Doporučené + Populární + Nejlepší + Nové + 30 $ nebo méně + Jiné + Pro všechny věkové skupiny + Teenageři + Pro dospělé + Dokončeno + Předběžný přístup + Hry partnerů + Prohlížeč + Věkové hodnocení + Stav + Partneři + Sledované hry diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 7ce1ae1d45..2d4082298e 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -3606,4 +3606,33 @@ Reparer filer Opdater installationen Vælg + Ikke i dit Game Jolt-bibliotek + Ingen Windows-download til dette spil + Der blev ikke fundet et Windows-spil i downloaden + Kunne ikke finde dette spil på Game Jolt + Kunne ikke hente spil fra Game Jolt + Game Jolt svarede HTTP %1$d + Kunne ikke indlæse downloads fra Game Jolt + Åbn på Game Jolt + %1$s-arkiver understøttes ikke + Downloaden kunne ikke udpakkes (kode %1$d) + Kunne ikke nå Game Jolt + Game Jolt gav ikke et downloadlink + Fremhævede + Populære + Bedste + Nye + $30 eller mindre + Andet + Alle aldre + Teenagere + Voksne + Færdige + Early access + Partnerspil + Browser + Modenhed + Status + Partnere + Fulgte spil diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index c2a250fb1a..8157b7e1ea 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -3606,4 +3606,33 @@ Dateien reparieren Installation erneuern Auswählen + Nicht in deiner Game Jolt-Bibliothek + Kein Windows-Download für dieses Spiel + Im Download wurde kein Windows-Spiel gefunden + Dieses Spiel wurde auf Game Jolt nicht gefunden + Spiele von Game Jolt konnten nicht geladen werden + Game Jolt antwortete mit HTTP %1$d + Die Downloads von Game Jolt konnten nicht geladen werden + Auf Game Jolt öffnen + %1$s-Archive werden nicht unterstützt + Download konnte nicht entpackt werden (Code %1$d) + Game Jolt ist nicht erreichbar + Game Jolt hat keinen Download-Link geliefert + Empfohlen + Angesagt + Beste + Neu + 30 $ oder weniger + Andere + Alle Altersgruppen + Jugendliche + Erwachsene + Fertig + Early Access + Partnerspiele + Browser + Altersfreigabe + Status + Partner + Gefolgte Spiele diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 72d2b9356d..a627bc4168 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -3606,4 +3606,33 @@ Επιδιόρθωση αρχείων Ανανέωση εγκατάστασης Επιλογή + Δεν είναι στη βιβλιοθήκη σας στο Game Jolt + Δεν υπάρχει λήψη για Windows για αυτό το παιχνίδι + Δεν βρέθηκε παιχνίδι Windows στη λήψη + Δεν βρέθηκε αυτό το παιχνίδι στο Game Jolt + Δεν ήταν δυνατή η φόρτωση παιχνιδιών από το Game Jolt + Το Game Jolt απάντησε HTTP %1$d + Δεν ήταν δυνατή η φόρτωση των λήψεων από το Game Jolt + Άνοιγμα στο Game Jolt + Τα αρχεία %1$s δεν υποστηρίζονται + Δεν ήταν δυνατή η αποσυμπίεση της λήψης (κωδικός %1$d) + Δεν ήταν δυνατή η σύνδεση με το Game Jolt + Το Game Jolt δεν έδωσε σύνδεσμο λήψης + Προτεινόμενα + Δημοφιλή + Καλύτερα + Νέα + 30$ ή λιγότερο + Άλλα + Όλες οι ηλικίες + Έφηβοι + Ενήλικες + Ολοκληρωμένα + Πρώιμη πρόσβαση + Παιχνίδια συνεργατών + Πρόγραμμα περιήγησης + Ωριμότητα + Κατάσταση + Συνεργάτες + Παιχνίδια που ακολουθείτε diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index e084f25ead..a3247ba1cd 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -3643,4 +3643,33 @@ Reparar archivos Renovar la instalación Seleccionar + No está en tu biblioteca de Game Jolt + No hay descarga para Windows de este juego + No se ha encontrado un juego de Windows en la descarga + No se ha encontrado este juego en Game Jolt + No se pudieron cargar los juegos de Game Jolt + Game Jolt respondió HTTP %1$d + No se pudieron cargar las descargas de Game Jolt + Abrir en Game Jolt + Los archivos %1$s no son compatibles + No se ha podido extraer la descarga (código %1$d) + No se pudo conectar con Game Jolt + Game Jolt no proporcionó un enlace de descarga + Destacados + Populares + Mejores + Nuevos + 30 $ o menos + Otros + Todas las edades + Adolescentes + Adultos + Completo + Acceso anticipado + Juegos de socios + Navegador + Clasificación + Estado + Socios + Juegos seguidos diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index dc52bc46eb..a733c907c8 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -3606,4 +3606,33 @@ Korjaa tiedostot Päivitä asennus Valitse + Ei Game Jolt-kirjastossasi + Ei Windows-latausta tälle pelille + Latauksesta ei löytynyt Windows-peliä + Peliä ei löytynyt Game Joltista + Pelien lataaminen Game Joltista epäonnistui + Game Jolt vastasi HTTP %1$d + Latausten haku Game Joltista epäonnistui + Avaa Game Joltissa + %1$s-arkistot eivät ole tuettuja + Latausta ei voitu purkaa (koodi %1$d) + Game Joltiin ei saatu yhteyttä + Game Jolt ei antanut latauslinkkiä + Esittelyssä + Kuumat + Parhaat + Uudet + 30 $ tai alle + Muu + Kaikenikäisille + Nuoret + Aikuiset + Valmis + Ennakkojulkaisu + Kumppanien pelit + Selain + Ikärajat + Tila + Kumppanit + Seuratut pelit diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 8d52998f0c..a59fa6f5ca 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -3643,4 +3643,33 @@ Réparer les fichiers Actualiser l\'installation Sélectionner + Absent de votre bibliothèque Game Jolt + Pas de téléchargement Windows pour ce jeu + Aucun jeu Windows trouvé dans le téléchargement + Ce jeu est introuvable sur Game Jolt + Impossible de charger les jeux de Game Jolt + Game Jolt a répondu HTTP %1$d + Impossible de charger les téléchargements depuis Game Jolt + Ouvrir sur Game Jolt + Les archives %1$s ne sont pas prises en charge + Impossible d\'extraire le téléchargement (code %1$d) + Impossible de joindre Game Jolt + Game Jolt n\'a pas fourni de lien de téléchargement + À la une + Tendances + Meilleurs + Nouveaux + 30 $ ou moins + Autre + Tous publics + Adolescents + Adultes + Terminé + Accès anticipé + Jeux partenaires + Navigateur + Classification + Statut + Partenaires + Jeux suivis diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 632e1a8066..c6325ed999 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -3606,4 +3606,33 @@ फ़ाइलें रिपेयर करें इंस्टॉलेशन रिफ़्रेश करें चुनें + आपकी Game Jolt लाइब्रेरी में नहीं + इस गेम के लिए Windows डाउनलोड नहीं है + डाउनलोड में कोई Windows गेम नहीं मिला + यह गेम Game Jolt पर नहीं मिला + Game Jolt से गेम लोड नहीं हो सके + Game Jolt ने HTTP %1$d लौटाया + Game Jolt से डाउनलोड लोड नहीं हो सके + Game Jolt पर खोलें + %1$s आर्काइव समर्थित नहीं हैं + डाउनलोड एक्सट्रैक्ट नहीं हो सका (कोड %1$d) + Game Jolt तक नहीं पहुँचा जा सका + Game Jolt ने डाउनलोड लिंक नहीं दिया + फ़ीचर्ड + लोकप्रिय + सर्वश्रेष्ठ + नए + $30 या उससे कम + अन्य + सभी उम्र + किशोर + वयस्क + पूर्ण + अर्ली एक्सेस + पार्टनर गेम + ब्राउज़र + आयु वर्ग + स्थिति + पार्टनर + फ़ॉलो किए गए गेम diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 200d5410bf..f35b74f262 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -3606,4 +3606,33 @@ Fájlok javítása Telepítés frissítése Kiválasztás + Nincs a Game Jolt-könyvtáradban + Ehhez a játékhoz nincs Windows-letöltés + A letöltésben nem található Windows-játék + A játék nem található a Game Jolt-on + Nem sikerült betölteni a játékokat a Game Jolt-ról + A Game Jolt HTTP %1$d választ adott + A letöltések betöltése a Game Jolt-ról nem sikerült + Megnyitás a Game Jolt-on + A(z) %1$s archívumok nem támogatottak + A letöltés nem bontható ki (kód: %1$d) + A Game Jolt nem érhető el + A Game Jolt nem adott letöltési hivatkozást + Kiemelt + Népszerű + Legjobb + Új + 30 $ vagy kevesebb + Egyéb + Minden korosztály + Tinédzserek + Felnőtt + Kész + Korai hozzáférés + Partnerjátékok + Böngésző + Korhatár + Állapot + Partnerek + Követett játékok diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 8f1b2d4f64..90d529218a 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -3578,4 +3578,33 @@ Perbaiki file Segarkan instalasi Pilih + Tidak ada di pustaka Game Jolt Anda + Tidak ada unduhan Windows untuk game ini + Tidak ada game Windows di unduhan + Game ini tidak ditemukan di Game Jolt + Tidak dapat memuat game dari Game Jolt + Game Jolt menjawab HTTP %1$d + Tidak dapat memuat unduhan dari Game Jolt + Buka di Game Jolt + Arsip %1$s tidak didukung + Tidak dapat mengekstrak unduhan (kode %1$d) + Tidak dapat menghubungi Game Jolt + Game Jolt tidak memberikan tautan unduhan + Unggulan + Sedang tren + Terbaik + Baru + $30 atau kurang + Lainnya + Semua umur + Remaja + Dewasa + Selesai + Akses awal + Game mitra + Peramban + Klasifikasi usia + Status + Mitra + Game yang diikuti diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index eef6c71a96..2a0664db65 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -3643,4 +3643,33 @@ Ripara file Aggiorna installazione Seleziona + Non è nella tua libreria Game Jolt + Nessun download per Windows di questo gioco + Nessun gioco Windows trovato nel download + Gioco non trovato su Game Jolt + Impossibile caricare i giochi da Game Jolt + Game Jolt ha risposto HTTP %1$d + Impossibile caricare i download da Game Jolt + Apri su Game Jolt + Gli archivi %1$s non sono supportati + Impossibile estrarre il download (codice %1$d) + Impossibile raggiungere Game Jolt + Game Jolt non ha fornito un link di download + In evidenza + Di tendenza + Migliori + Nuovi + 30 $ o meno + Altro + Per tutti + Adolescenti + Adulti + Completo + Accesso anticipato + Giochi dei partner + Browser + Classificazione + Stato + Partner + Giochi seguiti diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 4dfbf1888c..ed27707c11 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -3578,4 +3578,33 @@ ファイルを修復 インストールを更新 選択 + Game Jolt ライブラリにありません + このゲームには Windows 版のダウンロードがありません + ダウンロードに Windows 版のゲームが見つかりません + Game Jolt でこのゲームが見つかりませんでした + Game Jolt のゲームを読み込めませんでした + Game Jolt が HTTP %1$d を返しました + Game Jolt からダウンロードを読み込めませんでした + Game Jolt で開く + %1$s 形式のアーカイブには対応していません + ダウンロードを展開できませんでした (終了コード %1$d) + Game Jolt に接続できませんでした + Game Jolt がダウンロードリンクを提供しませんでした + 注目 + 人気急上昇 + ベスト + 新着 + 30ドル以下 + その他 + 全年齢 + ティーン + 成人向け + 完成 + アーリーアクセス + パートナーのゲーム + ブラウザ + 対象年齢 + ステータス + パートナー + フォロー中のゲーム diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 84502f7e7b..821641cab2 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -3578,4 +3578,33 @@ 파일 복구 설치 새로 고침 선택 + Game Jolt 라이브러리에 없습니다 + 이 게임의 Windows 다운로드가 없습니다 + 다운로드에서 Windows 게임을 찾을 수 없습니다 + Game Jolt에서 이 게임을 찾을 수 없습니다 + Game Jolt에서 게임을 불러오지 못했습니다 + Game Jolt가 HTTP %1$d을(를) 반환했습니다 + Game Jolt에서 다운로드를 불러오지 못했습니다 + Game Jolt에서 열기 + %1$s 압축 파일은 지원하지 않습니다 + 다운로드한 파일의 압축을 풀 수 없습니다(코드 %1$d) + Game Jolt에 연결할 수 없습니다 + Game Jolt에서 다운로드 링크를 제공하지 않았습니다 + 추천 + 인기 + 베스트 + 신규 + $30 이하 + 기타 + 전체 이용가 + 청소년 + 성인 + 완성 + 앞서 해보기 + 파트너 게임 + 브라우저 + 연령 등급 + 상태 + 파트너 + 팔로우한 게임 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index bdae3d8784..1d2b2ff463 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -3578,4 +3578,33 @@ Baik pulih fail Segar semula pemasangan Pilih + Tiada dalam pustaka Game Jolt anda + Tiada muat turun Windows untuk permainan ini + Tiada permainan Windows ditemui dalam muat turun + Permainan ini tidak ditemui di Game Jolt + Tidak dapat memuatkan permainan daripada Game Jolt + Game Jolt menjawab HTTP %1$d + Tidak dapat memuatkan muat turun daripada Game Jolt + Buka di Game Jolt + Arkib %1$s tidak disokong + Tidak dapat mengekstrak muat turun (kod %1$d) + Tidak dapat menghubungi Game Jolt + Game Jolt tidak memberikan pautan muat turun + Pilihan + Hangat + Terbaik + Baharu + $30 atau kurang + Lain-lain + Semua peringkat umur + Remaja + Dewasa + Siap + Akses awal + Permainan rakan kongsi + Pelayar + Kematangan + Status + Rakan kongsi + Permainan diikuti diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index f21e994d70..c0ecc73a29 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -3606,4 +3606,33 @@ Reparer filer Oppdater installasjonen Velg + Ikke i Game Jolt-biblioteket ditt + Ingen Windows-nedlasting for dette spillet + Fant ikke noe Windows-spill i nedlastingen + Fant ikke dette spillet på Game Jolt + Kunne ikke laste spill fra Game Jolt + Game Jolt svarte HTTP %1$d + Kunne ikke laste inn nedlastingene fra Game Jolt + Åpne på Game Jolt + %1$s-arkiver støttes ikke + Kunne ikke pakke ut nedlastingen (kode %1$d) + Kunne ikke nå Game Jolt + Game Jolt ga ingen nedlastingslenke + Fremhevet + Populære + Beste + Nye + $30 eller mindre + Annet + Alle aldre + Tenåringer + Voksne + Ferdig + Early access + Partnerspill + Nettleser + Aldersgrense + Status + Partnere + Fulgte spill diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 9eba9f0047..576631973c 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -3606,4 +3606,33 @@ Bestanden repareren Installatie vernieuwen Kiezen + Niet in je Game Jolt-bibliotheek + Geen Windows-download voor dit spel + Geen Windows-game gevonden in de download + Deze game is niet gevonden op Game Jolt + Games van Game Jolt konden niet worden geladen + Game Jolt antwoordde HTTP %1$d + De downloads van Game Jolt konden niet worden geladen + Openen op Game Jolt + %1$s-archieven worden niet ondersteund + Download kan niet worden uitgepakt (code %1$d) + Game Jolt is niet bereikbaar + Game Jolt gaf geen downloadlink + Uitgelicht + Populair + Beste + Nieuw + $30 of minder + Overig + Alle leeftijden + Tieners + Volwassenen + Voltooid + Early access + Partnerspellen + Browser + Leeftijdsklasse + Status + Partners + Gevolgde games diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 92941eeaf3..93b8a830ed 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -3680,4 +3680,33 @@ Napraw pliki Odśwież instalację Wybierz + Nie ma go w Twojej bibliotece Game Jolt + Brak wersji na Windows dla tej gry + W pobranych plikach nie znaleziono gry na Windows + Nie znaleziono tej gry w Game Jolt + Nie udało się wczytać gier z Game Jolt + Game Jolt odpowiedziało HTTP %1$d + Nie udało się wczytać plików z Game Jolt + Otwórz w Game Jolt + Archiwa %1$s nie są obsługiwane + Nie można rozpakować pobranego pliku (kod %1$d) + Nie można połączyć się z Game Jolt + Game Jolt nie podał linku do pobrania + Polecane + Na czasie + Najlepsze + Nowe + 30 $ lub mniej + Inne + Dla wszystkich + Nastolatki + Dla dorosłych + Ukończone + Wczesny dostęp + Gry partnerów + Przeglądarka + Kategoria wiekowa + Status + Partnerzy + Obserwowane gry diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index ac8eac1e03..5640c1c578 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -3643,4 +3643,33 @@ Reparar ficheiros Renovar instalação Selecionar + Não está na sua biblioteca do Game Jolt + Sem transferência para Windows deste jogo + Não foi encontrado nenhum jogo para Windows na transferência + Não foi possível encontrar este jogo no Game Jolt + Não foi possível carregar os jogos do Game Jolt + O Game Jolt respondeu HTTP %1$d + Não foi possível carregar as transferências do Game Jolt + Abrir no Game Jolt + Ficheiros %1$s não são suportados + Não foi possível extrair a transferência (código %1$d) + Não foi possível aceder ao Game Jolt + O Game Jolt não forneceu uma ligação de transferência + Em destaque + Em alta + Melhores + Novos + 30 $ ou menos + Outros + Todas as idades + Adolescentes + Adulto + Completo + Acesso antecipado + Jogos de parceiros + Navegador + Classificação + Estado + Parceiros + Jogos seguidos diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index b3d20eb86b..fa704f1e34 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -3643,4 +3643,33 @@ Reparar arquivos Renovar instalação Selecionar + Não está na sua biblioteca do Game Jolt + Sem download para Windows deste jogo + Nenhum jogo para Windows encontrado no download + Não foi possível encontrar este jogo no Game Jolt + Não foi possível carregar os jogos do Game Jolt + O Game Jolt respondeu HTTP %1$d + Não foi possível carregar os downloads do Game Jolt + Abrir no Game Jolt + Arquivos %1$s não são suportados + Não foi possível extrair o download (código %1$d) + Não foi possível acessar o Game Jolt + O Game Jolt não forneceu um link de download + Em destaque + Em alta + Melhores + Novos + US$ 30 ou menos + Outros + Todas as idades + Adolescentes + Adulto + Completo + Acesso antecipado + Jogos de parceiros + Navegador + Classificação + Status + Parceiros + Jogos seguidos diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 0ad675136f..fafe91aab3 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -3643,4 +3643,33 @@ Repară fișierele Reîmprospătează instalarea Selectează + Nu este în biblioteca ta Game Jolt + Nu există descărcare pentru Windows la acest joc + Nu s-a găsit niciun joc Windows în descărcare + Jocul nu a fost găsit pe Game Jolt + Nu s-au putut încărca jocurile de pe Game Jolt + Game Jolt a răspuns HTTP %1$d + Descărcările de pe Game Jolt nu au putut fi încărcate + Deschide pe Game Jolt + Arhivele %1$s nu sunt acceptate + Descărcarea nu a putut fi extrasă (cod %1$d) + Nu s-a putut contacta Game Jolt + Game Jolt nu a oferit un link de descărcare + Recomandate + În tendințe + Cele mai bune + Noi + 30 $ sau mai puțin + Altele + Toate vârstele + Adolescenți + Adulți + Finalizat + Acces anticipat + Jocuri partenere + Browser + Maturitate + Stare + Parteneri + Jocuri urmărite diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 17df27216a..d31b5b54ab 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -3680,4 +3680,33 @@ Восстановить файлы Обновить установку Выбрать + Нет в вашей библиотеке Game Jolt + Для этой игры нет загрузки для Windows + В загрузке не найдена игра для Windows + Не удалось найти эту игру на Game Jolt + Не удалось загрузить игры с Game Jolt + Game Jolt ответил HTTP %1$d + Не удалось загрузить список файлов с Game Jolt + Открыть на Game Jolt + Архивы %1$s не поддерживаются + Не удалось распаковать загрузку (код %1$d) + Не удалось связаться с Game Jolt + Game Jolt не предоставил ссылку для скачивания + Рекомендуемые + Популярные + Лучшие + Новые + 30 $ или дешевле + Другое + Для всех возрастов + Подростки + Для взрослых + Завершена + Ранний доступ + Игры партнёров + Браузер + Возрастной рейтинг + Статус + Партнёры + Отслеживаемые игры diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 946ce4fc41..645c25857d 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -3606,4 +3606,33 @@ Reparera filer Uppdatera installationen Välj + Inte i ditt Game Jolt-bibliotek + Ingen Windows-nedladdning för det här spelet + Inget Windows-spel hittades i nedladdningen + Spelet hittades inte på Game Jolt + Det gick inte att läsa in spel från Game Jolt + Game Jolt svarade HTTP %1$d + Det gick inte att läsa in nedladdningarna från Game Jolt + Öppna på Game Jolt + %1$s-arkiv stöds inte + Det gick inte att packa upp nedladdningen (kod %1$d) + Det gick inte att nå Game Jolt + Game Jolt gav ingen nedladdningslänk + Utvalda + Populära + Bästa + Nya + $30 eller mindre + Övrigt + Alla åldrar + Tonåringar + Vuxna + Färdigt + Tidig åtkomst + Partnerspel + Webbläsare + Åldersgräns + Status + Partner + Följda spel diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 30e69f2e71..41318ab7c5 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -3578,4 +3578,33 @@ ซ่อมแซมไฟล์ รีเฟรชการติดตั้ง เลือก + ไม่มีในคลัง Game Jolt ของคุณ + เกมนี้ไม่มีการดาวน์โหลดสำหรับ Windows + ไม่พบเกม Windows ในไฟล์ที่ดาวน์โหลด + ไม่พบเกมนี้บน Game Jolt + โหลดเกมจาก Game Jolt ไม่ได้ + Game Jolt ตอบกลับ HTTP %1$d + โหลดรายการดาวน์โหลดจาก Game Jolt ไม่ได้ + เปิดบน Game Jolt + ไม่รองรับไฟล์ %1$s + แตกไฟล์ที่ดาวน์โหลดไม่ได้ (รหัส %1$d) + ไม่สามารถเชื่อมต่อ Game Jolt ได้ + Game Jolt ไม่ได้ให้ลิงก์ดาวน์โหลด + แนะนำ + มาแรง + ยอดนิยมสูงสุด + ใหม่ + $30 หรือต่ำกว่า + อื่น ๆ + ทุกวัย + วัยรุ่น + ผู้ใหญ่ + เสร็จสมบูรณ์ + เข้าถึงก่อนใคร + เกมของพาร์ตเนอร์ + เบราว์เซอร์ + ระดับเนื้อหา + สถานะ + พาร์ตเนอร์ + เกมที่ติดตาม diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index a1f6116e09..e8347fab3d 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -3606,4 +3606,33 @@ Dosyaları onar Kurulumu yenile Seç + Game Jolt kütüphanenizde yok + Bu oyunun Windows indirmesi yok + İndirmede Windows oyunu bulunamadı + Bu oyun Game Jolt\'ta bulunamadı + Game Jolt oyunları yüklenemedi + Game Jolt HTTP %1$d yanıtı verdi + İndirmeler Game Jolt\'tan yüklenemedi + Game Jolt\'ta aç + %1$s arşivleri desteklenmiyor + İndirme ayıklanamadı (kod %1$d) + Game Jolt\'a ulaşılamadı + Game Jolt bir indirme bağlantısı vermedi + Öne çıkanlar + Popüler + En iyiler + Yeni + 30 $ veya daha az + Diğer + Her yaş + Gençler + Yetişkin + Tamamlandı + Erken erişim + Ortak oyunlar + Tarayıcı + Yaş sınırı + Durum + Ortaklar + Takip edilen oyunlar diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index e901908359..d4aa241f24 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -3680,4 +3680,33 @@ Відновити файли Оновити встановлення Вибрати + Немає у вашій бібліотеці Game Jolt + Для цієї гри немає завантаження для Windows + У завантаженні не знайдено гри для Windows + Не вдалося знайти цю гру на Game Jolt + Не вдалося завантажити ігри з Game Jolt + Game Jolt відповів HTTP %1$d + Не вдалося завантажити список файлів з Game Jolt + Відкрити на Game Jolt + Архіви %1$s не підтримуються + Не вдалося розпакувати завантаження (код %1$d) + Не вдалося зв\'язатися з Game Jolt + Game Jolt не надав посилання для завантаження + Рекомендовані + Популярні + Найкращі + Нові + 30 $ або менше + Інше + Для всіх віків + Підлітки + Для дорослих + Завершена + Рання версія + Ігри партнерів + Браузер + Вікова категорія + Статус + Партнери + Ігри, за якими ви стежите diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 2a7c052951..a93d71508c 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -3578,4 +3578,33 @@ Sửa tệp Làm mới bản cài Chọn + Không có trong thư viện Game Jolt của bạn + Không có bản tải Windows cho game này + Không tìm thấy trò chơi Windows trong bản tải xuống + Không tìm thấy trò chơi này trên Game Jolt + Không tải được game từ Game Jolt + Game Jolt trả về HTTP %1$d + Không thể tải danh sách tải xuống từ Game Jolt + Mở trên Game Jolt + Không hỗ trợ tệp %1$s + Không thể giải nén bản tải xuống (mã %1$d) + Không thể kết nối với Game Jolt + Game Jolt không cung cấp liên kết tải xuống + Nổi bật + Thịnh hành + Hay nhất + Mới + $30 trở xuống + Khác + Mọi lứa tuổi + Thanh thiếu niên + Người lớn + Hoàn chỉnh + Truy cập sớm + Game của đối tác + Trình duyệt + Độ tuổi + Trạng thái + Đối tác + Game đang theo dõi diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 17aee27ba7..8808906445 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -3578,4 +3578,33 @@ 修复文件 刷新安装 选择 + 不在你的 Game Jolt 库中 + 这个游戏没有 Windows 下载 + 下载内容中未找到 Windows 游戏 + 在 Game Jolt 上找不到这款游戏 + 无法从 Game Jolt 加载游戏 + Game Jolt 返回 HTTP %1$d + 无法从 Game Jolt 加载下载内容 + 在 Game Jolt 上打开 + 不支持 %1$s 压缩包 + 无法解压下载内容(代码 %1$d) + 无法连接到 Game Jolt + Game Jolt 未提供下载链接 + 精选 + 热门 + 最佳 + 最新 + 30 美元以下 + 其他 + 全年龄 + 青少年 + 成人 + 已完成 + 抢先体验 + 合作伙伴游戏 + 浏览器 + 内容分级 + 状态 + 合作伙伴 + 已关注的游戏 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index ffb08a1189..095cb890c3 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -3578,4 +3578,33 @@ 修復檔案 重新整理安裝 選擇 + 不在你的 Game Jolt 收藏庫中 + 這個遊戲沒有 Windows 下載 + 下載內容中找不到 Windows 遊戲 + 在 Game Jolt 找不到這款遊戲 + 無法從 Game Jolt 載入遊戲 + Game Jolt 回應 HTTP %1$d + 無法從 Game Jolt 載入下載內容 + 在 Game Jolt 開啟 + 不支援 %1$s 壓縮檔 + 無法解壓下載內容(代碼 %1$d) + 無法連線至 Game Jolt + Game Jolt 沒有提供下載連結 + 精選 + 熱門 + 最佳 + 最新 + 30 美元或以下 + 其他 + 全年齡 + 青少年 + 成人 + 已完成 + 搶先體驗 + 合作夥伴遊戲 + 瀏覽器 + 內容分級 + 狀態 + 合作夥伴 + 已追蹤的遊戲 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index f914d0eedb..56005e1ff8 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -3578,4 +3578,33 @@ 修復檔案 重新整理安裝 選取 + 不在你的 Game Jolt 收藏庫中 + 這個遊戲沒有 Windows 下載 + 下載內容中找不到 Windows 遊戲 + 在 Game Jolt 找不到這款遊戲 + 無法從 Game Jolt 載入遊戲 + Game Jolt 回應 HTTP %1$d + 無法從 Game Jolt 載入下載內容 + 在 Game Jolt 開啟 + 不支援 %1$s 壓縮檔 + 無法解壓縮下載內容(代碼 %1$d) + 無法連線至 Game Jolt + Game Jolt 未提供下載連結 + 精選 + 熱門 + 最佳 + 最新 + 30 美元或以下 + 其他 + 全年齡 + 青少年 + 成人 + 已完成 + 搶先體驗 + 合作夥伴遊戲 + 瀏覽器 + 內容分級 + 狀態 + 合作夥伴 + 已追蹤的遊戲 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index bbef6462a8..6f88608575 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -3683,4 +3683,33 @@ %1$s and %2$d more Restart now Later + Not in your Game Jolt library + No Windows download for this game + No Windows game found in the download + Could not find this game on Game Jolt + Could not load games from Game Jolt + Game Jolt answered HTTP %1$d + Could not load the downloads from Game Jolt + Open on Game Jolt + Could not reach Game Jolt + Game Jolt did not give a download link + %1$s archives are not supported + Could not extract the download (exit %1$d) + Featured + Hot + Best + New + $30 or less + Other + All ages + Teen + Mature + Complete + Early access + Partner games + Browser + Maturity + Status + Partners + Followed games diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreInstallRootTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreInstallRootTest.kt index 09cf7fc265..c368ca082b 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/StoreInstallRootTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreInstallRootTest.kt @@ -298,4 +298,9 @@ class StoreInstallRootTest { assertFalse(StoreInstallRoot.insufficientSpace(1L, 1L)) assertFalse(StoreInstallRoot.insufficientSpace(0L, 0L)) } + + @Test fun itchKeepsTheFolderItsGamesWereInstalledInWhateverItsDisplayName() { + assertEquals("itch", StoreInstallRoot.storeDir(File("/games"), Store.ITCH).name) + assertEquals("Game Jolt", StoreInstallRoot.storeDir(File("/games"), Store.GAMEJOLT).name) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBrowseTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBrowseTest.kt new file mode 100644 index 0000000000..97b90c6da2 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBrowseTest.kt @@ -0,0 +1,36 @@ +package com.droiddeck.launcher.stores.gamejolt + +import org.junit.Assert.assertEquals +import org.junit.Test + +class GameJoltBrowseTest { + private fun qs(query: GameJoltQuery = GameJoltQuery(), page: Int = 1) = GameJoltBrowse.queryString(query, page) + + @Test fun theDefaultQueryAsksForTheFeaturedSectionByName() { + assertEquals("section=featured", qs()) + } + + @Test fun sectionsPriceAndPagesUseTheSiteNames() { + assertEquals("section=hot", qs(GameJoltQuery(section = GameJoltBrowse.SECTION_HOT))) + assertEquals("section=featured&f_price=5-less&page=3", qs(GameJoltQuery(price = GameJoltBrowse.PRICE_UNDER_5), 3)) + assertEquals("section=featured&f_price=free", qs(GameJoltQuery(price = GameJoltBrowse.PRICE_FREE))) + } + + @Test fun listFiltersKeepTheSiteOrderWhateverTheSelectionOrder() { + assertEquals("section=featured&f_os%5B%5D=windows&f_os%5B%5D=linux", qs(GameJoltQuery(os = setOf("linux", "windows")))) + assertEquals("section=featured&f_browser%5B%5D=html&f_maturity%5B%5D=everyone&f_status%5B%5D=complete&f_partners%5B%5D=partners", + qs(GameJoltQuery(browser = setOf("html"), maturity = setOf("everyone"), status = setOf("complete"), partners = true))) + } + + @Test fun devlogGamesAreNeverAskedFor() { + assertEquals(setOf("complete", "wip"), GameJoltBrowse.effective(GameJoltQuery(), true).status) + assertEquals(setOf("complete", "wip"), GameJoltBrowse.effective(GameJoltQuery(status = setOf("devlog")), true).status) + assertEquals(setOf("wip"), GameJoltBrowse.effective(GameJoltQuery(status = setOf("wip", "devlog")), false).status) + assertEquals("section=featured&f_status%5B%5D=complete&f_status%5B%5D=wip", qs(GameJoltBrowse.effective(GameJoltQuery(), true).copy(maturity = emptySet()))) + } + + @Test fun tagsAreSluggedAndRepeatable() { + assertEquals("co-op", GameJoltBrowse.tagSlug(" Co-Op ")) + assertEquals("section=featured&tag=action&tag=co-op", qs(GameJoltQuery(tags = listOf("Action", "co op")))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBuildsTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBuildsTest.kt new file mode 100644 index 0000000000..7f20f12fd7 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltBuildsTest.kt @@ -0,0 +1,41 @@ +package com.droiddeck.launcher.stores.gamejolt + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) +@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class) +class GameJoltBuildsTest { + private fun build(id: Int, pkg: Int, release: Int, name: String, vararg flags: String) = JSONObject() + .put("id", id).put("game_package_id", pkg).put("game_release_id", release) + .put("primary_file", JSONObject().put("filename", name).put("filesize", 100)) + .also { b -> flags.forEach { b.put(it, true) } } + + private fun payload(vararg builds: JSONObject) = JSONObject() + .put("packages", JSONArray().put(JSONObject().put("id", 1).put("title", "Main"))) + .put("releases", JSONArray().put(JSONObject().put("id", 10).put("published_on", 100).put("version_number", "1.0")).put(JSONObject().put("id", 11).put("published_on", 200).put("version_number", "1.1"))) + .put("builds", JSONArray(builds.toList())) + .put("launchOptions", JSONArray()) + + @Test fun onlyTheNewestReleaseOfAPackageIsKept() { + val list = GameJoltBuilds.parse(payload(build(1, 1, 10, "old.zip", "os_windows"), build(2, 1, 11, "new.zip", "os_windows"))) + assertEquals(listOf("2"), list.map { it.id }) + assertEquals("1.1", list.first().version) + } + + @Test fun windowsBuildsAreInstallableAndSortFirst() { + val list = GameJoltBuilds.parse(payload(build(1, 1, 11, "game-linux.zip", "os_linux"), build(2, 1, 11, "game-win.zip", "os_windows"))) + assertEquals(listOf("2", "1"), list.map { it.id }) + assertTrue(list[0].installable) + assertFalse(list[1].installable) + } + + @Test fun aBuildWithoutAnOsFlagIsWeb() { + assertEquals(setOf("web"), GameJoltBuilds.platforms(JSONObject())) + assertEquals(setOf("windows", "osx"), GameJoltBuilds.platforms(JSONObject().put("os_windows", true).put("os_mac", true))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltCollectionsTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltCollectionsTest.kt new file mode 100644 index 0000000000..0e8e1d1ee4 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltCollectionsTest.kt @@ -0,0 +1,28 @@ +package com.droiddeck.launcher.stores.gamejolt + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) +@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class) +class GameJoltCollectionsTest { + @Test fun playlistsBecomeCollectionsByIdAndName() { + val list = JSONArray() + .put(JSONObject().put("id", 7).put("name", "test list")) + .put(JSONObject().put("id", 0).put("name", "no id")) + .put(JSONObject().put("id", 9).put("name", "")) + val parsed = GameJoltCollections.parse(list) + assertEquals(listOf("playlist:7"), parsed.map { it.id }) + assertEquals(listOf("test list"), parsed.map { it.title }) + } + + @Test fun eachCollectionHasItsOwnGameListEndpoint() { + assertEquals("/web/library/games/followed/@some+one", GameJoltCollections.path(GameJoltCollections.FOLLOWED, "some one")) + assertEquals("/web/library/games/playlist/7", GameJoltCollections.path("playlist:7", "x")) + assertNull(GameJoltCollections.path("playlist:abc", "x")) + assertNull(GameJoltCollections.path("other", "x")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltPricingTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltPricingTest.kt new file mode 100644 index 0000000000..48c2f85024 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltPricingTest.kt @@ -0,0 +1,52 @@ +package com.droiddeck.launcher.stores.gamejolt + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) +@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class) +class GameJoltPricingTest { + private fun pricing(amount: Long, promotional: Boolean = false, currency: Any = JSONObject.NULL) = + JSONObject().put("amount", amount).put("promotional", promotional).put("currency_code", currency) + + private fun sellable(vararg pricings: JSONObject) = JSONObject().put("type", "paid").put("pricings", JSONArray(pricings.toList())) + + @Test fun aRegularPriceIsShownInDollars() { + val price = GameJoltPricing.of(sellable(pricing(99)))!! + assertEquals("$0.99", price.final) + assertEquals("", price.original) + assertEquals(0, price.discount) + } + + @Test fun aPromotionalPriceBesideTheRegularOneIsASale() { + val price = GameJoltPricing.of(sellable(pricing(500), pricing(350, promotional = true)))!! + assertEquals("$3.50", price.final) + assertEquals("$5.00", price.original) + assertEquals(30, price.discount) + } + + @Test fun aPromotionalPriceAloneShowsNoDiscount() { + val price = GameJoltPricing.of(sellable(pricing(350, promotional = true)))!! + assertEquals("$3.50", price.final) + assertEquals("", price.original) + assertEquals(0, price.discount) + } + + @Test fun aPromotionalPriceNotBelowTheRegularOneIsNotASale() { + val price = GameJoltPricing.of(sellable(pricing(500), pricing(500, promotional = true)))!! + assertEquals("", price.original) + assertEquals(0, price.discount) + } + + @Test fun aGameWithoutPricingsHasNoPrice() { + assertNull(GameJoltPricing.of(sellable())) + assertNull(GameJoltPricing.of(null)) + } + + @Test fun anotherCurrencyIsNamed() { + assertEquals("1.50 EUR", GameJoltPricing.of(sellable(pricing(150, currency = "EUR")))!!.final) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltUpdatesTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltUpdatesTest.kt new file mode 100644 index 0000000000..109da6c362 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/gamejolt/GameJoltUpdatesTest.kt @@ -0,0 +1,63 @@ +package com.droiddeck.launcher.stores.gamejolt + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) +@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class) +class GameJoltUpdatesTest { + private fun build(id: String, pkg: String, stamp: String, windows: Boolean = true, name: String = "game.zip") = + GameJoltBuild(id, pkg, "Main", "1.0", name, 100L, stamp, if (windows) setOf("windows") else setOf("linux"), "", "") + + @Test fun aNewerReleaseOfTheSamePackageIsAnUpdate() { + val update = GameJoltUpdates.evaluate(listOf(build("20", "1", "200", name = "new.zip")), "10", "1", "100")!! + assertEquals("20", update.buildId) + assertEquals("new.zip", update.filename) + assertFalse(update.replaced) + } + + @Test fun theInstalledBuildIsNotAnUpdate() { + assertNull(GameJoltUpdates.evaluate(listOf(build("10", "1", "100")), "10", "1", "100")) + } + + @Test fun anOlderBuildIsNotAnUpdate() { + assertNull(GameJoltUpdates.evaluate(listOf(build("5", "1", "50")), "10", "1", "100")) + } + + @Test fun theSameReleaseTimeWithAHigherBuildIdIsAnUpdate() { + assertEquals("11", GameJoltUpdates.evaluate(listOf(build("11", "1", "100")), "10", "1", "100")?.buildId) + } + + @Test fun otherPackagesDoNotCount() { + assertEquals("30", GameJoltUpdates.evaluate(listOf(build("40", "2", "900"), build("30", "1", "300")), "10", "1", "100")?.buildId) + } + + @Test fun aRemovedPackageFallsBackToTheNewPreferredBuildAndSaysSo() { + val update = GameJoltUpdates.evaluate(listOf(build("40", "2", "900")), "10", "1", "100")!! + assertEquals("40", update.buildId) + assertTrue(update.replaced) + } + + @Test fun nonWindowsBuildsAreNeverOffered() { + assertNull(GameJoltUpdates.evaluate(listOf(build("40", "1", "900", windows = false)), "10", "1", "100")) + } + + @Test fun nothingToCompareMeansNoUpdate() { + assertNull(GameJoltUpdates.evaluate(null, "10", "1", "100")) + assertNull(GameJoltUpdates.evaluate(listOf(build("40", "1", "900")), "", "1", "100")) + } + + @Test fun foundUpdatesSurviveEncodingAndDropEntriesWithoutABuild() { + val saved = GameJoltUpdates.encode(mapOf("gamejolt:1" to GameJoltUpdate("20", "200", "new.zip", true))) + val back = GameJoltUpdates.decode(saved).getValue("gamejolt:1") + assertEquals("20", back.buildId) + assertEquals("200", back.stamp) + assertEquals("new.zip", back.filename) + assertTrue(back.replaced) + assertEquals(emptyMap(), GameJoltUpdates.decode("""{"gamejolt:1":{"stamp":"1"}}""")) + assertEquals(emptyMap(), GameJoltUpdates.decode("not json")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt index d703d09bec..7674ab242d 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt @@ -87,6 +87,11 @@ class LibraryEntriesTest { assertEquals(listOf("epic", "gog", "battlenet"), librarySources(entries, listOf("missing", "epic", "epic", "amazon"))) } + @Test fun aSignedInStoreWithNoGamesKeepsItsPlaceInTheStoreOrder() { + val entries = listOf("steam", "xbox").map { LibraryEntry(it, it, it, null, null, true) } + assertEquals(listOf("steam", "xbox", "itch", "gamejolt"), librarySources(entries, listOf("xbox", "itch", "gamejolt"), setOf("itch", "gamejolt"))) + } + @Test fun gameKeysNameEitherAnAppOrAStoreProduct() { GameRef.parse("app:440").let { assertEquals(440, it.appId); assertNull(it.store) } GameRef.parse("app:-12").let { assertEquals(-12, it.appId) } diff --git a/docs/development/gamejolt-store.md b/docs/development/gamejolt-store.md new file mode 100644 index 0000000000..ae8ca0f456 --- /dev/null +++ b/docs/development/gamejolt-store.md @@ -0,0 +1,66 @@ +# Game Jolt store + +The Game Jolt Store tab mirrors the itch.io one: browse, search, game page, build picker, installs, library, collections and updates. + +## Sign-in + +Game Jolt shows the normal sign-in card until an account is signed in. Signing in opens +`StoreLoginActivity` on `https://gamejolt.com/login` (`GameJoltLogin`). The flow is not a token redirect: +Game Jolt is a single-page site, so `StoreLoginActivity.Client.doUpdateVisitedHistory` also reports +navigations, and any gamejolt.com page outside the sign-in, sign-up and legal paths counts as signed in. +`finish` reads the WebView cookies, asks `/web/search/games?q=a` for the top-level `user`, and stores +the cookie header and the user through `GameJoltAuth` (encrypted, `StoreAccounts`). The log names the +cookies and the user keys, never their values. + +## Data + +`GameJoltApi` talks to `https://gamejolt.com/site-api/web/...` with the stored cookies. Games come back as +`{payload, user}`; `GameJoltCatalog` turns a game into a `CatalogItem` (paid only when `sellable.type` is +`paid`). + +Browse queries (`GameJoltBrowse.queryString`): `section=` is always sent first (featured, hot, best, new). +Game Jolt answers 404 to any browse request without it, even an empty one. The rest are `tag=`, `f_price=`, +and `f_os[]`, `f_browser[]`, `f_maturity[]`, `f_status[]`, `f_partners[]`, `page=`. Every page logs its query, +status and game count. The filters are drop-down menus (`BrowseDropdown`, shared with the itch bar). Devlog games have no playable +copy, so the status filter only offers complete and early access, and a browse always asks for those two. With mature +content off, `adult` is stripped from the query, including a stored one. + +## Prices + +`GameJoltPricing.of` reads `sellable.pricings[]` (amounts in cents). The promotional entry is the current price +and the regular entry the original, only when the original is higher; the percent uses integer math. USD (or no +currency) formats as `$12.34`, another currency as `12.34 EUR`. `CatalogItem` carries `finalPrice`, +`originalPrice` and `discountPercent`, so tiles and the game page show prices and sale badges. + +## Library and collections + +`GameJoltLibrary.sync` fetches `/web/library/games/owned/@` (paged, at most every ten minutes, forced by +the refresh action) and merges the games into the store library as owned. `GameJoltCollections` lists the +read-only collections: followed games (`/web/library/games/followed/@`) and the account's playlists +(`/web/library/games/playlist/`). The Library page shows them through the same `CollectionsButton` as itch. +Ownership comes from `sellables[0].is_owned`; `packages[0].is_game_owner` is not reliable. Library chips list a store when it has games in +the list; a signed-in Itch.io or Game Jolt account keeps its chip, in store order, so its collections stay reachable. + +## Builds and installs + +`GameJoltBuilds.parse` reads the overview payload, keeps the newest release of each package and marks +Windows builds installable. The picker (`GameJoltBuildPicker`) installs Windows builds of free games and of paid games the account owns; +Linux builds say "Not supported yet" and everything else, including paid games not owned, opens the Game Jolt page. +`GameJoltInstaller` asks `builds/get-download-url/` for a signed link on every attempt, resumes with +`Range`, unpacks through `StoreArchiveUnpacker` (shared with itch) and picks the launch option or an exe. +An update downloads again and merges through `ItchStaging`, like itch. + +## Updates + +`GameJoltUpdates` works like `ItchUpdates` (see `itch-updates.md`). The install record keeps the release +`published_on` as `installVersion` and `gameId`, `buildId` and `packageId` in `extra`. `evaluate` compares them +with the current builds: a newer release of the same package is an update; if the package is gone, the first +installable Windows build is offered as a replaced build. The automatic check runs when the Game Jolt Library +source opens, at most every six hours, one game per second. A Check for updates button on an installed game's page +checks that game only. Updates stage through `ItchStaging` and the safe folder. Uninstalling or finishing an +install clears the record. Install folders use `Store.folder`, so the Itch.io display name never moves them. + +## Controller + +The menus, chips and buttons are the shared components (`MenuItem`, `AnchoredMenu`, `ValueChip`, `BrowseChip`, +`IconAction`) that already take focus and confirm from a controller. The first menu entry takes initial focus.