diff --git a/README.md b/README.md index a2a8cdaa9f..09a3a828ba 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - The Recomps tab lists the three community catalogs below, read straight from their sites. Each entry shows which catalog it came from. - [Decomp Buddy](https://decompbuddy.com) ([TanookiStudios/decomp-buddy](https://github.com/TanookiStudios/decomp-buddy), GPL-3.0) by Maddie at [Tanooki Studios](https://tanookistudios.com): its `catalog.json` and `plans.json` supply most entries, their exact release files, programs and scanned checksums, and the game files each needs. Matching a PC port to a Steam, GOG or Epic install follows its `src/stores.js` title rules, and arm64 Linux files are found the way its `armSibling` finds them. When a project's own download is gone, DroidDeck falls back to Decomp Buddy's scanned copy ([donate](https://decompbuddy.com/donate) to keep those online). - [Recomp Launcher](https://recomplauncher.com) ([elripalda/RecompLauncher](https://github.com/elripalda/RecompLauncher), GPL-3.0) by [@elripalda](https://github.com/elripalda), [@Xarishark](https://github.com/Xarishark) and contributors: its `pc-catalog.json` supplies the Windows and Linux recomps, their release pins and checksums, start programs, setup notes and the game data each needs. + - A PC game's Steam, GOG and Epic IDs come from [Wikidata](https://www.wikidata.org) (CC0), by the IGDB slug Recomp Launcher gives, and GOG product slugs from GOG's public products API. - [Recompa](https://recompa.app) ([kalasyan/recompa](https://github.com/kalasyan/recompa), GPL-3.0) by [@kalasyan](https://github.com/kalasyan): its `index.json` supplies the Android ports, their APK checksums, package names and signing certificates, and the ROMs or files each needs. - Every game's build is downloaded from its own developers' releases and keeps its own licence. DroidDeck ships no ROMs or game files. diff --git a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt index eaa3140e8b..ffac9f19b9 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt @@ -102,8 +102,8 @@ private fun RecompsTab(): Unit { ) val states: Map = mapOf( "zelda64recomp" to RecompData.State.BringYourOwn(list[0].data), - "ironwail" to RecompData.State.Found(Store.STEAM, java.io.File("/q"), "/root/.local/share/Steam/steamapps/common/Quake"), - "fallout2-ce" to RecompData.State.Owned(Store.GOG, null), + "ironwail" to RecompData.State.Found(Store.STEAM, java.io.File("/q"), "/root/.local/share/Steam/steamapps/common/Quake", exact = true, checked = true), + "fallout2-ce" to RecompData.State.Owned(Store.GOG, null, exact = true), "shipwright" to RecompData.State.BringYourOwn(list[3].data), ) val installed = mapOf("zelda64recomp" to com.droiddeck.launcher.runtime.RecompInstaller.Installed( diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DecompBuddyPlans.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DecompBuddyPlans.kt index 5cd139a350..25824c9ef8 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DecompBuddyPlans.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DecompBuddyPlans.kt @@ -8,7 +8,10 @@ import java.io.Reader // Decomp Buddy's plans.json (about 16 MB) holds, per repo and platform, the release file to download, the // program in it and the game files it needs. It is read as a stream, keeping only those fields. object DecompBuddyPlans { - class GameFile(val label: String, val filename: String?, val how: String?, val kind: String?) + class GameFile( + val label: String, val filename: String?, val how: String?, val kind: String?, + val hashes: List> = emptyList(), val size: Long = 0, + ) class Target( val gameTitle: String?, val method: String?, val asset: String?, val tag: String?, val executable: String?, @@ -108,16 +111,30 @@ object DecompBuddyPlans { while (r.hasNext()) { if (r.peek() != JsonToken.BEGIN_OBJECT) { r.skipValue(); continue } var label = ""; var name: String? = null; var how: String? = null; var kind: String? = null + val hashes = mutableListOf>(); var size = 0L r.beginObject() while (r.hasNext()) when (r.nextName()) { "label" -> label = r.str().orEmpty() "expected_filename" -> name = r.str() "how_provided" -> how = r.str() "kind" -> kind = r.str() + "expected_size" -> size = if (r.peek() == JsonToken.NUMBER) r.nextLong() else { r.skipValue(); 0L } + "expected_hashes" -> if (r.peek() != JsonToken.BEGIN_ARRAY) r.skipValue() else { + r.beginArray() + while (r.hasNext()) { + if (r.peek() != JsonToken.BEGIN_OBJECT) { r.skipValue(); continue } + var algo: String? = null; var value: String? = null + r.beginObject() + while (r.hasNext()) when (r.nextName()) { "algo" -> algo = r.str(); "value" -> value = r.str(); else -> r.skipValue() } + r.endObject() + if (algo != null && value != null) hashes += algo to value + } + r.endArray() + } else -> r.skipValue() } r.endObject() - files += GameFile(label, name, how, kind) + files += GameFile(label, name, how, kind, hashes, size) } r.endArray() } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/RecompCatalog.kt b/app/src/main/java/com/droiddeck/launcher/runtime/RecompCatalog.kt index 25672ba440..4856984de2 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/RecompCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/RecompCatalog.kt @@ -48,14 +48,20 @@ object RecompCatalog { enum class DataKind { ROM, DUMP, NONE } - // [file] is the name a plan expects inside the game's folder, which finds the folder in a store install. - class Data(val kind: DataKind, val label: String, val sha1: List = emptyList(), val note: String = "", val file: String? = null) + class Hash(val algo: String, val value: String) + + // [file] is a file the port needs inside the game's folder (a relative path), which finds that folder in a + // store install; [hashes] and [size], when a catalog gives them, tell the right version of it from another. + class Data( + val kind: DataKind, val label: String, val sha1: List = emptyList(), val note: String = "", val file: String? = null, + val hashes: List = emptyList(), val size: Long = 0, + ) class Entry( val id: String, val name: String, val game: String, val origin: String, val type: String, val repo: String, val license: String, val homepage: String, val art: String?, val builds: List, val data: Data, - val sources: List, val popularity: Long = 0, val setup: String? = null, + val sources: List, val popularity: Long = 0, val setup: String? = null, val igdb: String? = null, ) { fun build(platform: Platform) = builds.firstOrNull { it.platform == platform } @@ -75,11 +81,11 @@ object RecompCatalog { fun read(feed: Feed, parse: (File) -> List): List = files[feed]?.let { f -> runCatching { parse(f) }.onFailure { Log.w(TAG, "${feed.id}: $it") }.getOrNull() }.orEmpty() val plans = files[DECOMP_BUDDY_PLANS]?.let { f -> runCatching { DecompBuddyPlans.read(f) }.onFailure { Log.w(TAG, "plans: $it") }.getOrNull() }.orEmpty() - val list = merge( + val list = shareIgdb(merge( read(DECOMP_BUDDY) { fromDecompBuddy(JSONObject(it.readText()), plans) }, read(RECOMP_LAUNCHER) { fromRecompLauncher(JSONObject(it.readText())) }, read(RECOMPA) { fromRecompa(JSONObject(it.readText())) }, - ) + )) if (list.isNotEmpty()) cached = list return list } @@ -131,6 +137,20 @@ object RecompCatalog { private fun safeName(s: String?) = s?.takeIf { it.isNotEmpty() && '/' !in it && it != "." && it != ".." } + // A file path inside the game's folder: relative, forward slashes, no parent steps. + internal fun safePath(s: String?): String? = s?.replace('\\', '/')?.trim('/') + ?.takeIf { p -> p.isNotEmpty() && p.split('/').none { it.isEmpty() || it == "." || it == ".." } && ':' !in p } + + private val HASH_ALGOS = mapOf("sha1" to 40, "sha256" to 64, "md5" to 32, "crc32" to 8) + + internal fun hash(algo: String?, value: String?): Hash? { + val a = algo?.lowercase() ?: return null + val v = value?.lowercase()?.takeIf { HASH_ALGOS[a] == it.length && it.all { c -> c in "0123456789abcdef" } } ?: return null + return Hash(a, v) + } + + private val IGDB_URL = Regex("^https?://(?:www\\.)?igdb\\.com/games/([a-z0-9-]+)/?$") + private fun sha256(s: String?) = s?.lowercase()?.takeIf { SHA256.matches(it) } internal fun globRegex(glob: String) = @@ -183,7 +203,8 @@ object RecompCatalog { val data = when { needs == null -> Data(DataKind.NONE, "") else -> Data(if (origin in PC_ORIGINS) DataKind.DUMP else DataKind.ROM, needs.label, note = g.str("description").orEmpty(), - file = needs.filename?.takeIf { needs.how == "folder" || needs.how == "command_line" }?.let { safeName(it) }) + file = needs.filename?.takeIf { needs.how == "folder" || needs.how == "command_line" }?.let { safePath(it) }, + hashes = needs.hashes.mapNotNull { (a, v) -> hash(a, v) }, size = needs.size) } val id = g.str("slug") ?: return null return Entry( @@ -224,6 +245,11 @@ object RecompCatalog { } if (builds.isEmpty()) return null val what = boot.optJSONObject("files")?.str("what") ?: a.str("needs") + val inputs = a.optJSONObject("launcher")?.optJSONArray("inputs") + val game = (0 until (inputs?.length() ?: 0)).mapNotNull { inputs!!.optJSONObject(it) } + .firstOrNull { (it.str("role") ?: "game") == "game" || it.str("id") == "game" } + val check = game?.optJSONObject("check")?.str("file")?.let { safePath(it) } + val igdb = a.optJSONObject("about")?.str("url")?.let { IGDB_URL.find(it)?.groupValues?.get(1) } val steps = a.optJSONArray("setup_steps") val id = a.str("id") ?: return null val setup = if (!a.optBoolean("setup_required")) null @@ -232,8 +258,8 @@ object RecompCatalog { id, a.str("name") ?: id, a.str("game") ?: a.str("name") ?: id, origin(a.str("origin").orEmpty()), if ("recomp" in (id + repo).lowercase()) "recomp" else "port", repo, a.str("license").orEmpty(), "https://github.com/$repo", a.str("icon") ?: a.str("cover"), builds, - if (what != null) Data(DataKind.DUMP, what, note = a.str("blurb").orEmpty()) else Data(DataKind.NONE, ""), - listOf(RECOMP_LAUNCHER.id), a.optLong("downloads"), setup, + if (what != null) Data(DataKind.DUMP, what, note = a.str("blurb").orEmpty(), file = check) else Data(DataKind.NONE, ""), + listOf(RECOMP_LAUNCHER.id), a.optLong("downloads"), setup, igdb, ) } @@ -280,6 +306,20 @@ object RecompCatalog { ) } + // An IGDB slug names the game, not the port, so other ports of a PC game take it from the one that has it, + // when the game's title leads to a single slug. + internal fun shareIgdb(list: List): List { + val slugs = list.filter { it.pc && it.igdb != null }.groupBy { RecompData.norm(it.game) } + .mapValues { (_, v) -> v.mapNotNull { it.igdb }.distinct().singleOrNull() } + return list.map { e -> + if (!e.pc || e.igdb != null) e + else slugs[RecompData.norm(e.game)]?.let { slug -> + Entry(e.id, e.name, e.game, e.origin, e.type, e.repo, e.license, e.homepage, e.art, e.builds, e.data, e.sources, + e.popularity, e.setup, slug) + } ?: e + } + } + // An earlier catalog wins every field it sets; a later one with the same repo (or id) adds builds it lacks. internal fun merge(vararg catalogs: List): List { val out = LinkedHashMap() @@ -294,15 +334,15 @@ object RecompCatalog { val builds = base.builds.map { b -> e.build(b.platform)?.takeIf { b.platform == Platform.ANDROID && b.signer == null && it.signer != null && it.pkg == b.pkg } ?: b } + e.builds.filter { b -> base.builds.none { it.platform == b.platform } } - val data = when { - base.data.kind == DataKind.NONE -> e.data - base.data.sha1.isEmpty() && e.data.sha1.isNotEmpty() -> Data(base.data.kind, base.data.label, e.data.sha1, base.data.note, base.data.file) - else -> base.data - } + val b = base.data + val data = if (b.kind == DataKind.NONE) e.data else Data( + b.kind, b.label, b.sha1.ifEmpty { e.data.sha1 }, b.note, + b.file ?: e.data.file, if (b.file != null) b.hashes else e.data.hashes, if (b.file != null) b.size else e.data.size, + ) out[base.id] = Entry( base.id, base.name, base.game, base.origin.ifEmpty { e.origin }, base.type, base.repo, base.license.ifEmpty { e.license }, base.homepage, base.art ?: e.art, builds, data, - (base.sources + e.sources).distinct(), maxOf(base.popularity, e.popularity), base.setup ?: e.setup, + (base.sources + e.sources).distinct(), maxOf(base.popularity, e.popularity), base.setup ?: e.setup, base.igdb ?: e.igdb, ) } return out.values.toList() diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/RecompData.kt b/app/src/main/java/com/droiddeck/launcher/runtime/RecompData.kt index ca99333ca0..80980f23ab 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/RecompData.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/RecompData.kt @@ -1,29 +1,39 @@ package com.droiddeck.launcher.runtime import android.content.Context +import com.droiddeck.launcher.core.FileUtils import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreInstallRoot import com.droiddeck.launcher.stores.StoresState import com.droiddeck.launcher.stores.steam.SteamClient import com.droiddeck.launcher.stores.steam.SteamLibraryFolders +import org.json.JSONObject import java.io.File +import java.security.MessageDigest +import java.util.zip.CRC32 -// The catalogs name the game a PC port needs but not its store ids, so ownership is matched by title against -// the player's own libraries. Console recomps need a dump, which no store sells, and are never matched. +// Whether the player already has the PC game a port needs. A store whose release IDs are known for the game +// (RecompStoreIds) is matched by ID only; any other store by title. A match counts once the file the catalog +// names is in the install, and is the right version when a catalog gives its hash or size. object RecompData { sealed class State { object NotNeeded : State() class BringYourOwn(val data: RecompCatalog.Data) : State() - class Found(val store: Store, val host: File, val guest: String) : State() - class Owned(val store: Store, val item: CatalogItem?) : State() + class Found(val store: Store, val host: File, val guest: String, val exact: Boolean, val checked: Boolean) : State() + class Incomplete(val store: Store, val host: File, val file: String, val wrongVersion: Boolean) : State() + class Owned(val store: Store, val item: CatalogItem?, val exact: Boolean) : State() } - class Install(val store: Store, val title: String, val host: File, val guest: String) + class Install(val store: Store, val id: String?, val title: String, val host: File, val guest: String) - class Owner(val store: Store, val title: String, val item: CatalogItem?) + class Owner(val store: Store, val id: String?, val title: String, val item: CatalogItem?) - class Inputs(val installs: List, val owned: List) + class Inputs( + val installs: List, val owned: List, + val ids: Map = emptyMap(), val gogSlugs: Map = emptyMap(), + val hasher: (File, String) -> String? = ::hashOf, val done: () -> Unit = {}, + ) // Decomp Buddy's rules (src/stores.js): "Fallout 2: A Post Nuclear Role Playing Game" is Fallout 2, "Fallout 2" is // not Fallout, a possessive in front ("Sid Meier's Civilization II") is dropped, and only store editions such as @@ -40,35 +50,102 @@ object RecompData { return n == t || listOf(":", " -", " –", " :").any { n.startsWith(t + it) } || (n.startsWith("$t ") && EDITION.matches(n.substring(t.length))) } - // The folder holding [name] (any case, up to 4 folders down), which is where the port expects to be pointed. - internal fun folderWith(dir: File, name: String): File? { - val want = name.lowercase() - val stack = ArrayDeque(listOf(dir to 0)) - while (stack.isNotEmpty()) { - val (d, depth) = stack.removeLast() - val entries = d.listFiles() ?: continue - if (entries.any { it.name.lowercase() == want }) return d - if (depth < 4) entries.filter { it.isDirectory }.forEach { stack.addLast(it to depth + 1) } + enum class Match { EXACT, TITLE } + + internal fun match(entry: RecompCatalog.Entry, inputs: Inputs, store: Store, id: String?, title: String): Match? { + val known = entry.igdb?.let { inputs.ids[it] }?.of(store).orEmpty() + if (known.isEmpty()) return if (sameGame(entry.game, title)) Match.TITLE else null + val key = when (store) { + Store.STEAM -> id + Store.GOG -> id?.let { inputs.gogSlugs[it] } + else -> null + } ?: return if (store == Store.EPIC && sameGame(entry.game, title)) Match.TITLE else null + return if (key.lowercase() in known) Match.EXACT else null + } + + // The file a catalog names, as a relative path matched without case, up to 4 folders below [dir]. + internal fun locate(dir: File, path: String): File? { + val parts = path.split('/').filter { it.isNotEmpty() } + if (parts.isEmpty()) return null + var level = listOf(dir) + repeat(5) { + for (d in level) resolve(d, parts)?.let { return it } + level = level.flatMap { d -> d.listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty() } } return null } - fun inputs(context: Context, steamOwned: Collection>): Inputs { + private fun resolve(base: File, parts: List): File? { + var cur = base + for ((i, part) in parts.withIndex()) { + val next = File(cur, part).takeIf { it.exists() } ?: cur.listFiles()?.firstOrNull { it.name.equals(part, ignoreCase = true) } ?: return null + if (i < parts.lastIndex && !next.isDirectory) return null + cur = next + } + return cur.takeIf { it.isFile } + } + + private fun folderOf(found: File, path: String): File { + var dir = found.parentFile!! + repeat(path.split('/').filter { it.isNotEmpty() }.size - 1) { dir = dir.parentFile ?: dir } + return dir + } + + private fun rightVersion(data: RecompCatalog.Data, file: File, hasher: (File, String) -> String?): Boolean { + if (data.size > 0 && file.length() != data.size) return false + if (data.hashes.isEmpty()) return true + return data.hashes.any { h -> hasher(file, h.algo)?.equals(h.value, ignoreCase = true) == true } + } + + fun resolve(entry: RecompCatalog.Entry, inputs: Inputs): State { + if (entry.pc) { + val file = entry.data.file + var incomplete: State.Incomplete? = null + val installs = inputs.installs.mapNotNull { i -> match(entry, inputs, i.store, i.id, i.title)?.let { i to it } } + .sortedBy { it.second.ordinal } + for ((install, how) in installs) { + if (file == null) return State.Found(install.store, install.host, install.guest, how == Match.EXACT, checked = false) + val found = locate(install.host, file) + if (found == null) { + incomplete = incomplete ?: State.Incomplete(install.store, install.host, file, wrongVersion = false) + continue + } + if (!rightVersion(entry.data, found, inputs.hasher)) { + incomplete = State.Incomplete(install.store, install.host, file, wrongVersion = true) + continue + } + val dir = folderOf(found, file) + val rel = dir.relativeTo(install.host).invariantSeparatorsPath.trim('/') + return State.Found(install.store, dir, if (rel.isEmpty() || rel == ".") install.guest else "${install.guest.trimEnd('/')}/$rel", + how == Match.EXACT, checked = true) + } + incomplete?.let { return it } + inputs.owned.mapNotNull { o -> match(entry, inputs, o.store, o.id, o.title)?.let { o to it } }.minByOrNull { it.second.ordinal } + ?.let { (o, how) -> return State.Owned(o.store, o.item, how == Match.EXACT) } + } + return if (entry.data.kind == RecompCatalog.DataKind.NONE) State.NotNeeded else State.BringYourOwn(entry.data) + } + + fun inputs(context: Context, steamOwned: Collection>, entries: List, offline: Boolean = false): Inputs { val root = LinuxRuntime.rootDir(context) val installs = mutableListOf() StoresState.installed.forEach { game -> - installs += Install(game.sidecar.store, game.sidecar.title, game.folder, guestPath(context, root, game.folder)) + installs += Install(game.sidecar.store, game.sidecar.id, game.sidecar.title, game.folder, guestPath(context, root, game.folder)) } runCatching { - SteamLibraryFolders.installed(SteamClient.libraries(context)).forEach { (_, app) -> + SteamLibraryFolders.installed(SteamClient.libraries(context)).forEach { (appId, app) -> val dir = app.installDir ?: return@forEach - installs += Install(Store.STEAM, app.name, File(app.library.host, "steamapps/common/$dir"), + installs += Install(Store.STEAM, appId.toString(), app.name, File(app.library.host, "steamapps/common/$dir"), "${app.library.guest.trimEnd('/')}/steamapps/common/$dir") } } - val owned = StoresState.library.flatMap { (store, list) -> list.filter { it.accessible }.map { Owner(store, it.title, it) } } + - steamOwned.map { (_, name) -> Owner(Store.STEAM, name, null) } - return Inputs(installs, owned) + val owned = StoresState.library.flatMap { (store, list) -> list.filter { it.accessible }.map { Owner(store, it.id, it.title, it) } } + + steamOwned.map { (appId, name) -> Owner(Store.STEAM, appId.toString(), name, null) } + val ids = runCatching { RecompStoreIds.forGames(context, entries.filter { it.pc }.mapNotNull { it.igdb }, offline) }.getOrDefault(emptyMap()) + val gogIds = installs.filter { it.store == Store.GOG }.mapNotNull { it.id } + owned.filter { it.store == Store.GOG }.mapNotNull { it.id } + val gogSlugs = if (ids.values.any { it.gog.isNotEmpty() }) runCatching { RecompStoreIds.gogSlugs(context, gogIds, offline) }.getOrDefault(emptyMap()) else emptyMap() + val hashes = HashCache(File(File(context.filesDir, "recomps"), "hashes.json")) + return Inputs(installs, owned, ids, gogSlugs, { f, algo -> hashes.get(f, algo) }, hashes::save) } private fun guestPath(context: Context, root: File, host: File): String { @@ -77,16 +154,31 @@ object RecompData { return if (h.startsWith("$r/")) h.removePrefix(r) else StoreInstallRoot.guestPath(context, host) } - fun resolve(entry: RecompCatalog.Entry, inputs: Inputs): State { - if (entry.pc) { - val file = entry.data.file - for (install in inputs.installs.filter { sameGame(entry.game, it.title) }) { - val dir = if (file == null) install.host else folderWith(install.host, file) ?: continue - val rel = dir.relativeTo(install.host).invariantSeparatorsPath.trim('/') - return State.Found(install.store, dir, if (rel.isEmpty()) install.guest else "${install.guest.trimEnd('/')}/$rel") - } - inputs.owned.firstOrNull { sameGame(entry.game, it.title) }?.let { return State.Owned(it.store, it.item) } + internal fun hashOf(file: File, algo: String): String? = runCatching { + if (algo == "crc32") { + val crc = CRC32() + file.inputStream().buffered(1 shl 16).use { input -> val buf = ByteArray(1 shl 16); while (true) { val n = input.read(buf); if (n < 0) break; crc.update(buf, 0, n) } } + "%08x".format(crc.value) + } else { + val md = MessageDigest.getInstance(when (algo) { "sha1" -> "SHA-1"; "sha256" -> "SHA-256"; "md5" -> "MD5"; else -> return@runCatching null }) + file.inputStream().buffered(1 shl 16).use { input -> val buf = ByteArray(1 shl 16); while (true) { val n = input.read(buf); if (n < 0) break; md.update(buf, 0, n) } } + md.digest().joinToString("") { "%02x".format(it) } + } + }.getOrNull() + + // Hashing a large game file is slow, so each answer is kept until the file's size or modified time changes. + private class HashCache(private val file: File) { + private val json = runCatching { JSONObject(file.readText()) }.getOrDefault(JSONObject()) + private var dirty = false + + fun get(f: File, algo: String): String? { + val key = "${f.absolutePath}|${f.length()}|${f.lastModified()}|$algo" + json.optString(key).takeIf { it.isNotEmpty() }?.let { return it } + return hashOf(f, algo)?.also { json.put(key, it); dirty = true } + } + + fun save() { + if (dirty) runCatching { file.parentFile?.mkdirs(); FileUtils.writeString(file, json.toString()) } } - return if (entry.data.kind == RecompCatalog.DataKind.NONE) State.NotNeeded else State.BringYourOwn(entry.data) } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/RecompStoreIds.kt b/app/src/main/java/com/droiddeck/launcher/runtime/RecompStoreIds.kt new file mode 100644 index 0000000000..715cb9197d --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/RecompStoreIds.kt @@ -0,0 +1,145 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.stores.Store +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder + +// None of the recomp catalogs names the store release a PC port needs, but Recomp Launcher's gives each game's +// IGDB slug. Wikidata links IGDB slugs (P5794) to Steam app IDs (P1733), GOG slugs (P2725) and Epic store slugs +// (P6278), and GOG's public products API gives the slug of each GOG product the player owns. Both answers are +// cached, so a game is looked up again only after [MAX_AGE_MS]. +object RecompStoreIds { + private const val TAG = "RecompStoreIds" + private const val MAX_AGE_MS = 14L * 24 * 60 * 60 * 1000 + private const val BATCH = 150 + private const val GOG_BATCH = 50 + private const val WIKIDATA = "https://query.wikidata.org/sparql" + + class Ids(val steam: Set, val gog: Set, val epic: Set) { + fun of(store: Store): Set = when (store) { + Store.STEAM -> steam + Store.GOG -> gog + Store.EPIC -> epic + else -> emptySet() + } + + val empty get() = steam.isEmpty() && gog.isEmpty() && epic.isEmpty() + } + + private fun file(context: Context, name: String) = File(File(context.filesDir, "recomps").apply { mkdirs() }, name) + + // IGDB slug -> the store IDs Wikidata has for that game; a slug Wikidata does not know maps to empty IDs. + fun forGames(context: Context, slugs: Collection, offline: Boolean = false): Map { + val cacheFile = file(context, "store-ids.json") + val cache = runCatching { JSONObject(cacheFile.readText()) }.getOrDefault(JSONObject()) + val now = System.currentTimeMillis() + val stale = slugs.distinct().filter { now - (cache.optJSONObject(it)?.optLong("at") ?: 0L) > MAX_AGE_MS } + if (!offline && stale.isNotEmpty()) { + var changed = false + for (chunk in stale.chunked(BATCH)) { + val found = runCatching { query(chunk) }.onFailure { Log.w(TAG, "wikidata: $it") }.getOrNull() ?: break + for (slug in chunk) { + val ids = found[slug] ?: Ids(emptySet(), emptySet(), emptySet()) + cache.put(slug, JSONObject().put("at", now).put("steam", JSONArray(ids.steam.toList())) + .put("gog", JSONArray(ids.gog.toList())).put("epic", JSONArray(ids.epic.toList()))) + } + changed = true + } + if (changed) FileUtils.writeString(cacheFile, cache.toString()) + } + return slugs.mapNotNull { slug -> cache.optJSONObject(slug)?.let { slug to idsOf(it) } }.toMap() + } + + private fun idsOf(o: JSONObject): Ids { + fun set(key: String) = o.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.getString(it) }.toSet() }.orEmpty() + return Ids(set("steam"), set("gog"), set("epic")) + } + + internal fun sparql(slugs: List): String { + val values = slugs.filter { Regex("[a-z0-9-]+").matches(it) }.joinToString(" ") { "\"$it\"" } + return "SELECT ?igdb ?steam ?gog ?epic WHERE { VALUES ?igdb { $values } ?item wdt:P5794 ?igdb . " + + "OPTIONAL { ?item wdt:P1733 ?steam } OPTIONAL { ?item wdt:P2725 ?gog } OPTIONAL { ?item wdt:P6278 ?epic } }" + } + + private fun query(slugs: List): Map { + val body = "query=" + URLEncoder.encode(sparql(slugs), "UTF-8") + "&format=json" + val conn = (URL(WIKIDATA).openConnection() as HttpURLConnection).apply { + requestMethod = "POST"; doOutput = true; connectTimeout = 15_000; readTimeout = 60_000 + setRequestProperty("User-Agent", "DroidDeck (https://github.com/Droid-Deck/DroidDeck)") + setRequestProperty("Accept", "application/sparql-results+json") + setRequestProperty("Content-Type", "application/x-www-form-urlencoded") + } + return try { + conn.outputStream.use { it.write(body.toByteArray()) } + if (conn.responseCode != 200) throw IllegalStateException("HTTP ${conn.responseCode}") + parseSparql(conn.inputStream.bufferedReader().use { it.readText() }) + } finally { + conn.disconnect() + } + } + + internal fun parseSparql(json: String): Map { + val rows = JSONObject(json).getJSONObject("results").getJSONArray("bindings") + val out = HashMap, MutableSet, MutableSet>>() + for (i in 0 until rows.length()) { + val row = rows.getJSONObject(i) + val slug = row.optJSONObject("igdb")?.optString("value") ?: continue + val (steam, gog, epic) = out.getOrPut(slug) { Triple(HashSet(), HashSet(), HashSet()) } + row.optJSONObject("steam")?.optString("value")?.takeIf { Regex("[0-9]+").matches(it) }?.let { steam += it } + row.optJSONObject("gog")?.optString("value")?.let { gogSlug(it) }?.let { gog += it } + row.optJSONObject("epic")?.optString("value")?.takeIf { it.isNotBlank() }?.let { epic += it.lowercase() } + } + return out.mapValues { (_, v) -> Ids(v.first, v.second, v.third) } + } + + // Wikidata writes GOG IDs as "game/" (or "movie/"); GOG's API gives the bare slug. + internal fun gogSlug(value: String): String? = value.substringAfterLast('/').lowercase().takeIf { Regex("[a-z0-9_]+").matches(it) } + + // GOG product ID -> slug, for the GOG products the player owns. Slugs do not change, so answers are kept. + fun gogSlugs(context: Context, ids: Collection, offline: Boolean = false): Map { + val cacheFile = file(context, "gog-slugs.json") + val cache = runCatching { JSONObject(cacheFile.readText()) }.getOrDefault(JSONObject()) + val missing = ids.filter { Regex("[0-9]+").matches(it) && !cache.has(it) }.distinct() + if (!offline && missing.isNotEmpty()) { + var changed = false + for (chunk in missing.chunked(GOG_BATCH)) { + val body = runCatching { get("https://api.gog.com/products?ids=${chunk.joinToString(",")}&locale=en-US") } + .onFailure { Log.w(TAG, "gog: $it") }.getOrNull() ?: break + val found = parseGogProducts(body) + for (id in chunk) cache.put(id, found[id] ?: "") + changed = true + } + if (changed) FileUtils.writeString(cacheFile, cache.toString()) + } + return ids.mapNotNull { id -> cache.optString(id).takeIf { it.isNotEmpty() }?.let { id to it } }.toMap() + } + + internal fun parseGogProducts(json: String): Map { + val arr = runCatching { JSONArray(json) }.getOrNull() ?: return emptyMap() + return (0 until arr.length()).mapNotNull { i -> + val o = arr.optJSONObject(i) ?: return@mapNotNull null + val id = o.opt("id")?.toString() ?: return@mapNotNull null + o.optString("slug").lowercase().takeIf { it.isNotEmpty() }?.let { id to it } + }.toMap() + } + + private fun get(url: String): String { + val conn = (URL(url).openConnection() as HttpURLConnection).apply { + connectTimeout = 15_000; readTimeout = 30_000 + setRequestProperty("User-Agent", "DroidDeck") + } + return try { + if (conn.responseCode != 200) throw IllegalStateException("HTTP ${conn.responseCode}") + conn.inputStream.bufferedReader().use { it.readText() } + } finally { + conn.disconnect() + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/store/RecompsState.kt b/app/src/main/java/com/droiddeck/launcher/store/RecompsState.kt index 2186493967..cf22cdda2b 100644 --- a/app/src/main/java/com/droiddeck/launcher/store/RecompsState.kt +++ b/app/src/main/java/com/droiddeck/launcher/store/RecompsState.kt @@ -53,8 +53,9 @@ object RecompsState { // Catalogs can rename an entry; an install also belongs to the entry with its repo. val byRepo = found.values.filter { it.repo != null }.associateBy { it.repo!!.lowercase() } val have = list.mapNotNull { e -> (found[e.id] ?: byRepo[e.repo.lowercase()])?.let { e.id to it } }.toMap() - val inputs = runCatching { RecompData.inputs(app, steamOwned) }.getOrNull() + val inputs = runCatching { RecompData.inputs(app, steamOwned, list) }.getOrNull() val states = list.associate { e -> e.id to (inputs?.let { RecompData.resolve(e, it) } ?: RecompData.State.BringYourOwn(e.data)) } + inputs?.done?.invoke() main.post { if (n != seq) return@post entries = list; installed = have; data = states; loading = false diff --git a/app/src/main/java/com/droiddeck/launcher/ui/RecompsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/RecompsPage.kt index a080b40a4c..aae61767d8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/RecompsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/RecompsPage.kt @@ -64,7 +64,7 @@ internal fun recompRows(): List = RecompsState.entries.map { e -> internal fun RecompRow.matches(filter: RecompFilter): Boolean = when (filter) { RecompFilter.ALL -> true - RecompFilter.OWNED -> data is RecompData.State.Found || data is RecompData.State.Owned + RecompFilter.OWNED -> data is RecompData.State.Found || data is RecompData.State.Owned || data is RecompData.State.Incomplete RecompFilter.INSTALLED -> installed != null RecompFilter.NATIVE -> (installed?.platform?.let { RecompCatalog.Platform.of(it) } ?: entry.preferred()?.platform) in NATIVE } @@ -82,7 +82,7 @@ private fun RecompRow.onSystem(system: String?) = system == null || entry.origin internal fun RecompRow.rank(): Int = when { installed != null -> 0 data is RecompData.State.Found -> 1 - data is RecompData.State.Owned -> 2 + data is RecompData.State.Owned || data is RecompData.State.Incomplete -> 2 else -> 3 } @@ -201,7 +201,15 @@ private fun sourceName(source: String): String? = when (source) { @Composable private fun dataLine(data: RecompData.State): Pair? = when (data) { RecompData.State.NotNeeded -> null - is RecompData.State.Found -> stringResource(R.string.recomps_data_found, storeName(data.store)) to true + is RecompData.State.Found -> when { + data.checked -> stringResource(R.string.recomps_data_found_checked, storeName(data.store)) to true + data.exact -> stringResource(R.string.recomps_data_found, storeName(data.store)) to true + else -> stringResource(R.string.recomps_data_found_by_name, storeName(data.store)) to false + } + is RecompData.State.Incomplete -> stringResource( + if (data.wrongVersion) R.string.recomps_data_wrong_version else R.string.recomps_data_missing_file, + storeName(data.store), data.file.substringAfterLast('/'), + ) to false is RecompData.State.Owned -> stringResource(R.string.recomps_data_owned, storeName(data.store)) to false is RecompData.State.BringYourOwn -> stringResource(R.string.recomps_data_bring, data.data.label.replace(Regex("^(your own |your )", RegexOption.IGNORE_CASE), "")) to false } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 751a96a6ee..5d3e454c3a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -4422,6 +4422,10 @@ No build DroidDeck can run Android app too Installed on %1$s + Installed on %1$s · files checked + Installed on %1$s · matched by name + Installed on %1$s, but %2$s is missing + Installed on %1$s, but %2$s is a different version You own it on %1$s. Install it first Needs your own %1$s Game folder: %1$s diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/RecompsTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/RecompsTest.kt index 9325755756..a61536e096 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/RecompsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/RecompsTest.kt @@ -26,7 +26,7 @@ class RecompsTest { "needs":"Your own copy of The Legend of Zelda: Majora's Mask","boot":{"kind":"portable","start":"Zelda64Recompiled.exe"}}, {"id":"ironwail","name":"Ironwail","game":"Quake","origin":"pc","repo":"andrei-drexler/ironwail","tag":"v0.8.2","downloads":10, "assets":{"linux":"ironwail-*-linux-x64.tar.gz","windows":"ironwail-*-win32.zip"},"boot":{"start_linux":"ironwail"}, - "needs":"Your Quake id1 folder"}, + "needs":"Your Quake id1 folder","about":{"igdb":333,"url":"https://www.igdb.com/games/quake"}}, {"id":"otherm","name":"Other M","origin":"wii","repo":"o/otherm","tag":"1.0","assets":{"windows":"OtherM.zip","linux":"OtherM-Flatpak.zip"}, "setup_required":true,"setup_steps":["Run setup.bat once.","Then play."]}, {"id":"gone","name":"Gone","repo":"o/gone","archived":true,"assets":{"windows":"g.zip"}}, @@ -110,13 +110,13 @@ class RecompsTest { } @Test fun pcPortsMatchOwnedGamesByTitleAndConsoleRecompsNever() { - val steam = RecompData.Install(Store.STEAM, "Quake", temporary.newFolder("Quake"), "/root/.local/share/Steam/steamapps/common/Quake") + val steam = RecompData.Install(Store.STEAM, "2310", "Quake", temporary.newFolder("Quake"), "/root/.local/share/Steam/steamapps/common/Quake") val found = RecompData.resolve(entry("ironwail"), RecompData.Inputs(listOf(steam), emptyList())) assertEquals("/root/.local/share/Steam/steamapps/common/Quake", (found as RecompData.State.Found).guest) val item = CatalogItem(Store.GOG, "1", "Quake", null) - assertTrue(RecompData.resolve(entry("ironwail"), RecompData.Inputs(emptyList(), listOf(RecompData.Owner(Store.GOG, "Quake™ GOTY Edition", item)))) is RecompData.State.Owned) - assertTrue(RecompData.resolve(entry("ironwail"), RecompData.Inputs(emptyList(), listOf(RecompData.Owner(Store.GOG, "Quake II", item)))) is RecompData.State.BringYourOwn) - val majora = RecompData.Install(Store.STEAM, "The Legend of Zelda: Majora's Mask", temporary.root, "/x") + assertTrue(RecompData.resolve(entry("ironwail"), RecompData.Inputs(emptyList(), listOf(RecompData.Owner(Store.GOG, "1", "Quake™ GOTY Edition", item)))) is RecompData.State.Owned) + assertTrue(RecompData.resolve(entry("ironwail"), RecompData.Inputs(emptyList(), listOf(RecompData.Owner(Store.GOG, "2", "Quake II", item)))) is RecompData.State.BringYourOwn) + val majora = RecompData.Install(Store.STEAM, "1", "The Legend of Zelda: Majora's Mask", temporary.root, "/x") assertTrue(RecompData.resolve(entry("zelda64recomp"), RecompData.Inputs(listOf(majora), emptyList())) is RecompData.State.BringYourOwn) } @@ -143,7 +143,8 @@ class RecompsTest { "github:diasurgical/devilutionx":{"tag":"1.5.5","generatedAt":"g","targets":{ "linux":{"redirect_repo":null,"games":[{"game_title":"Diablo","console":"PC","build":{"method":"release","release_asset":"devilutionx-linux-x86_64.tar.xz", "release_tag":"1.5.5","executable":"devilutionx","scanned":{"sha256":"${"1".repeat(64)}","size":1}}, - "game_files":[{"label":"DIABDAT.MPQ from Diablo","expected_filename":"DIABDAT.MPQ","how_provided":"folder","kind":"game","accepted_formats":[".mpq"]}], + "game_files":[{"label":"DIABDAT.MPQ from Diablo","expected_filename":"DIABDAT.MPQ","how_provided":"folder","kind":"game","accepted_formats":[".mpq"], + "expected_hashes":[{"algo":"MD5","value":"5D41402ABC4B2A76B9719D911017C592"},{"algo":"sha1","value":"not-a-hash"}],"expected_size":5}], "first_run":["a"],"notes":[],"mods":{"supported":false}}]}, "windows":{"games":[{"game_title":"Diablo","build":{"method":"release","release_asset":"devilutionx-windows-x86_64.zip","release_tag":"1.5.5", "executable":"bin\\devilutionx.exe","scanned":{"sha256":"${"2".repeat(64)}"}},"game_files":[]}]}, @@ -191,12 +192,99 @@ class RecompsTest { val d = RecompCatalog.fromDecompBuddy(decompBuddyFeed, plans).single() val gog = temporary.newFolder("Diablo GOG") File(gog, "hellfire").mkdirs() - File(gog, "hellfire/diabdat.mpq").writeText("x") - val install = RecompData.Install(Store.GOG, "Diablo + Hellfire".substringBefore(" +"), gog, "/root/Games/Stores/GOG/Diablo") + File(gog, "hellfire/diabdat.mpq").writeText("hello") + val install = RecompData.Install(Store.GOG, "1412601690", "Diablo + Hellfire".substringBefore(" +"), gog, "/root/Games/Stores/GOG/Diablo") val found = RecompData.resolve(d, RecompData.Inputs(listOf(install), emptyList())) - assertEquals("/root/Games/Stores/GOG/Diablo/hellfire", (found as RecompData.State.Found).guest) + found as RecompData.State.Found + assertEquals("/root/Games/Stores/GOG/Diablo/hellfire", found.guest) + assertTrue(found.checked) + File(gog, "hellfire/diabdat.mpq").writeText("jello") + val other = RecompData.resolve(d, RecompData.Inputs(listOf(install), emptyList())) + assertTrue((other as RecompData.State.Incomplete).wrongVersion) File(gog, "hellfire/diabdat.mpq").delete() - assertTrue(RecompData.resolve(d, RecompData.Inputs(listOf(install), emptyList())) is RecompData.State.BringYourOwn) + val missing = RecompData.resolve(d, RecompData.Inputs(listOf(install), emptyList())) as RecompData.State.Incomplete + assertEquals("DIABDAT.MPQ", missing.file) + assertTrue(!missing.wrongVersion) + } + + @Test fun catalogsGiveTheIgdbSlugTheNeededFileAndItsHashes() { + assertEquals("quake", entry("ironwail").igdb) + val plans = DecompBuddyPlans.read(java.io.StringReader(decompBuddyPlans)) + val d = RecompCatalog.fromDecompBuddy(decompBuddyFeed, plans).single().data + assertEquals(listOf("md5" to "5d41402abc4b2a76b9719d911017c592"), d.hashes.map { it.algo to it.value }) + assertEquals(5L, d.size) + val rl = RecompCatalog.fromRecompLauncher(JSONObject("""{"apps":[{"id":"f117","name":"F-117A","origin":"pc","repo":"o/f117","tag":"1", + "assets":{"windows":"f.zip"},"needs":"Your F-117A","launcher":{"inputs":[{"id":"game","label":"Your F-117A folder","check":{"file":"Data\\VGAME.EXE"}}]}}]}""")).single() + assertEquals("Data/VGAME.EXE", rl.data.file) + assertNull(RecompCatalog.safePath("../etc/passwd")) + assertNull(RecompCatalog.hash("sha1", "abc")) + } + + @Test fun wikidataAndGogAnswersParseToStoreIds() { + val ids = RecompStoreIds.parseSparql("""{"results":{"bindings":[ + {"igdb":{"value":"the-elder-scrolls-iii-morrowind"},"steam":{"value":"22320"},"gog":{"value":"game/the_elder_scrolls_iii_morrowind_goty_edition"},"epic":{"value":"morrowind-aa49c4"}}, + {"igdb":{"value":"the-elder-scrolls-iii-morrowind"},"steam":{"value":"22330"}}, + {"igdb":{"value":"diablo"},"gog":{"value":"game/diablo"}}]}}""") + val m = ids.getValue("the-elder-scrolls-iii-morrowind") + assertEquals(setOf("22320", "22330"), m.steam) + assertEquals(setOf("the_elder_scrolls_iii_morrowind_goty_edition"), m.gog) + assertEquals(setOf("morrowind-aa49c4"), m.epic) + assertTrue(ids.getValue("diablo").steam.isEmpty()) + assertTrue("\"quake\"" in RecompStoreIds.sparql(listOf("quake", "bad\" } evil"))) + assertTrue("evil" !in RecompStoreIds.sparql(listOf("quake", "bad\" } evil"))) + assertEquals(mapOf("1440163901" to "the_elder_scrolls_iii_morrowind_goty_edition", "1412601690" to "diablo"), + RecompStoreIds.parseGogProducts("""[{"id":1440163901,"slug":"the_elder_scrolls_iii_morrowind_goty_edition"},{"id":1412601690,"slug":"diablo"}]""")) + } + + @Test fun aKnownStoreIdIsMatchedExactlyAndATitleAloneIsNotEnoughThere() { + val quake = entry("ironwail") + val ids = mapOf("quake" to RecompStoreIds.Ids(setOf("2310"), setOf("quake_the_offering"), emptySet())) + fun state(vararg installs: RecompData.Install, owned: List = emptyList(), slugs: Map = emptyMap()) = + RecompData.resolve(quake, RecompData.Inputs(installs.toList(), owned, ids, slugs)) + val dir = temporary.newFolder("q") + val right = state(RecompData.Install(Store.STEAM, "2310", "Quake (Original)", dir, "/s/Quake")) + assertTrue((right as RecompData.State.Found).exact) + assertTrue(state(RecompData.Install(Store.STEAM, "9999", "Quake", dir, "/s/QuakeRemake")) is RecompData.State.BringYourOwn) + val gog = state(RecompData.Install(Store.GOG, "1", "Quake The Offering", dir, "/g/Quake"), slugs = mapOf("1" to "quake_the_offering")) + assertTrue((gog as RecompData.State.Found).exact) + val owned = state(owned = listOf(RecompData.Owner(Store.STEAM, "2310", "Something Else", null))) + assertTrue((owned as RecompData.State.Owned).exact) + val epicByName = state(RecompData.Install(Store.EPIC, "Quake", "Quake", dir, "/e/Quake")) + assertTrue(!(epicByName as RecompData.State.Found).exact) + } + + @Test fun aNeededFileCanSitInASubfolderPath() { + val e = RecompCatalog.Entry("openmw", "OpenMW", "The Elder Scrolls III: Morrowind", "PC", "port", "o/openmw", "", "", null, + listOf(RecompCatalog.Build(RecompCatalog.Platform.LINUX_X64, Regex("x"))), + RecompCatalog.Data(RecompCatalog.DataKind.DUMP, "Morrowind", file = "Data Files/Morrowind.esm"), listOf("recomp-launcher")) + val root = temporary.newFolder("Morrowind") + File(root, "data files").mkdirs() + File(root, "data files/MORROWIND.ESM").writeText("x") + val install = RecompData.Install(Store.STEAM, "22320", "The Elder Scrolls III: Morrowind GOTY Edition", root, "/s/Morrowind") + val found = RecompData.resolve(e, RecompData.Inputs(listOf(install), emptyList())) as RecompData.State.Found + assertEquals("/s/Morrowind", found.guest) + assertTrue(found.checked && !found.exact) + } + + @Test fun otherPortsOfAPcGameShareItsIgdbSlugOnlyWhenTheTitleIsUnambiguous() { + fun e(id: String, game: String, igdb: String?, origin: String = "PC") = RecompCatalog.Entry(id, id, game, origin, "port", "o/$id", "", "", null, + listOf(RecompCatalog.Build(RecompCatalog.Platform.LINUX_X64, Regex("x"))), RecompCatalog.Data(RecompCatalog.DataKind.NONE, ""), listOf("x"), igdb = igdb) + val out = RecompCatalog.shareIgdb(listOf( + e("ironwail", "Quake", "quake"), e("vkquake", "QUAKE", null), + e("doom-a", "Doom", "doom"), e("doom-b", "Doom", "doom--2"), e("doom-c", "Doom", null), + e("n64", "Quake", null, origin = "N64"), + )).associateBy { it.id } + assertEquals("quake", out.getValue("vkquake").igdb) + assertNull(out.getValue("doom-c").igdb) + assertNull(out.getValue("n64").igdb) + } + + @Test fun fileHashesUseTheCatalogsAlgorithms() { + val f = temporary.newFile("h").apply { writeText("hello") } + assertEquals("5d41402abc4b2a76b9719d911017c592", RecompData.hashOf(f, "md5")) + assertEquals("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d", RecompData.hashOf(f, "sha1")) + assertEquals("3610a686", RecompData.hashOf(f, "crc32")) + assertNull(RecompData.hashOf(f, "whirlpool")) } @Test fun theArm64TwinOfAnX64FileKeepsItsName() { diff --git a/docs/development/recomps.md b/docs/development/recomps.md index f35a5f299d..3ddb3ff5b1 100644 --- a/docs/development/recomps.md +++ b/docs/development/recomps.md @@ -106,22 +106,49 @@ The build is chosen in the order linux-arm64 (native), android, linux-x64 (FEX), ## Game data -For PC ports (Decomp Buddy's "PC (Windows)" and "IBM PC (MS-DOS)", Recomp Launcher's `pc`), `RecompData` -matches the game's title against the player's installs (store sidecars and Steam client libraries) and -owned games. It uses Decomp Buddy's rules: -- A subtitle after a colon or dash is fine, so "Fallout 2: A Post Nuclear Role Playing Game" is - Fallout 2. -- A leading possessive such as "Sid Meier's" is dropped. -- Only store-edition words (GOTY, Gold, Complete, Definitive, ...) may follow the title, so "Fallout 2" - is not "Fallout". +PC ports need the original PC game's files, which a store sells. For these entries (Decomp Buddy's "PC +(Windows)" and "IBM PC (MS-DOS)", Recomp Launcher's `pc` origin), DroidDeck works out whether the player +already has them. -Where a plan names the file the port needs in a folder (`expected_filename`, for example `DIABDAT.MPQ`), -the folder holding that file inside the install is the one shown. An install without that file does not -count. +**1. Which store release is the game: `RecompStoreIds`.** None of the catalogs names one. +- **IGDB slug:** Recomp Launcher gives each game's IGDB slug (`about.url`). Other ports of the same PC + game take it when the title leads to one slug (`shareIgdb`). That covers 390 of 1,104 PC entries. +- **Wikidata:** links IGDB slugs (P5794) to Steam app IDs (P1733), GOG slugs (P2725) and Epic store + slugs (P6278). It is asked in batches of 150 over SPARQL and cached in `files/recomps/store-ids.json` + for 14 days. 144 PC games get at least one store ID: 121 Steam, 90 GOG, 18 Epic. +- **GOG:** GOG's public products API (`api.gog.com/products?ids=…`, 50 per call) gives the slug of each + GOG product the player owns or installed. Kept in `gog-slugs.json`, since slugs don't change. -- **Installed:** "Installed on Steam" and the guest folder to point the port at. -- **Owned:** "Install game". -- **Otherwise:** what the catalog says the game needs. Console recomps are never matched. +**2. Matching an install or owned game.** +- For a store with known IDs for the game, only the ID counts: a Steam app ID, or a GOG product's slug. + A title match is not used there, so DOOM (2016) never stands in for Doom (1993). +- Epic IDs can't be compared yet: DroidDeck keeps an Epic game's namespace and app name, not its store + slug. So Epic, and any store without IDs for the game, falls back to Decomp Buddy's title rules (from + `src/stores.js`): + - A subtitle after a colon or dash is fine. + - A leading possessive such as "Sid Meier's" is dropped. + - Only store-edition words (GOTY, Gold, Complete, Definitive, ...) may follow the title. +- Installs come from store sidecars and the Steam client libraries, internal or SD card. Owned games + come from the store libraries and the Steam page. + +**3. The right files.** +- **The file:** Decomp Buddy's `expected_filename` or Recomp Launcher's `inputs[game].check.file` (112 + PC entries) names a file the port needs. It is looked for as a relative path, without case, up to 4 + folders into the install. The folder holding it is the one shown. +- **The version:** when Decomp Buddy gives `expected_hashes` (sha1, sha256, md5, crc32) or + `expected_size` (31 PC entries), the file must match. Hashes are kept in `hashes.json` by path, size + and modified time. + +| State | Card | +|---|---| +| Found, file checked | green "Installed on Steam · files checked", and the folder | +| Found by ID, no file to check | green "Installed on Steam" | +| Found by title only | grey "Installed on Steam · matched by name" | +| Incomplete | "Installed on GOG, but DIABDAT.MPQ is missing", or "… is a different version" | +| Owned | "You own it on Steam. Install it first", with "Install game" | +| Otherwise | what the catalog says the game needs | + +Console recomps are never matched, because no store sells their dumps. ## UI @@ -175,6 +202,9 @@ same code. - Zelda 64: Recompiled v1.2.2 installed from Decomp Buddy's `linux-arm64` plan in about 5 s and reached its Select ROM screen natively. +- AYN Thor, with store IDs: both Sonic Mania ports matched the Steam install on the SD card by app ID + (via IGDB and Wikidata), not by title. + ## Not done yet - **Recompa delivery rules.** Hand a chosen ROM to an Android port the way Recompa's `delivery` @@ -192,9 +222,10 @@ same code. - **ROM checks.** Hash a chosen ROM against `sha1` and say whether it is the right one. - **x86 runtime hint.** A linux-x64 build needs Steam opened once so the FEX runtime (sniper) is installed. Show that on the card, or fall back to the Windows build. -- **Steam ownership** relies on the Steam page's library or the Steam store sign-in. A game - installed by the Steam client counts as installed regardless. Title matching can miss renamed - editions. +- **Epic IDs.** Epic store slugs from Wikidata could be compared once DroidDeck keeps each owned Epic + game's product slug (Epic's catalog has it as `productSlug` / page mappings). +- **Store IDs upstream.** A `stores` field on Recomp Launcher inputs (Steam app IDs, GOG product IDs) + would make Wikidata a fallback. It has been proposed but not filed yet. - **Recomp setup steps.** Some recomps build themselves from the player's data with bundled Python (Recompia). They need executable storage, so they must stay inside the Linux root, never under `/media`; see the Discord thread on Recompia from 2026-11-15.