feat(recomps): match PC ports to owned games by store ID and check their files

The catalogs name no store release, but Recomp Launcher gives each game's
IGDB slug. Wikidata links IGDB slugs to Steam app IDs, GOG slugs and Epic
store slugs, and GOG's products API gives the slug of each owned GOG
product; both answers are cached. A store with known IDs for the game is
matched by ID only. Other ports of the same PC game share its slug.

A match counts once the file a catalog names is in the install, and is
the right version when Decomp Buddy gives its hash or size. The card says
whether files were checked, whether it matched only by name, or which
file is missing or different.
This commit is contained in:
Kurt Himebauch committed 2026-12-01 11:13:15 -05:00
1 parent e72496f34d
commit 9fee179a80
11 files changed
+509 -82

No files matched your search

@@ -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<Pair<String, String>> = 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<Pair<String, String>>(); 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()
}
@@ -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<String> = 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<String> = emptyList(), val note: String = "", val file: String? = null,
val hashes: List<Hash> = 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<Build>, val data: Data,
val sources: List<String>, val popularity: Long = 0, val setup: String? = null,
val sources: List<String>, 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 <T> read(feed: Feed, parse: (File) -> List<T>): List<T> =
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<Entry>): List<Entry> {
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<Entry>): List<Entry> {
val out = LinkedHashMap<String, Entry>()
@@ -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()
@@ -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<Install>, val owned: List<Owner>)
class Inputs(
val installs: List<Install>, val owned: List<Owner>,
val ids: Map<String, RecompStoreIds.Ids> = emptyMap(), val gogSlugs: Map<String, String> = 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<Pair<Int, String>>): Inputs {
private fun resolve(base: File, parts: List<String>): 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<Pair<Int, String>>, entries: List<RecompCatalog.Entry>, offline: Boolean = false): Inputs {
val root = LinuxRuntime.rootDir(context)
val installs = mutableListOf<Install>()
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)
}
}
@@ -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<String>, val gog: Set<String>, val epic: Set<String>) {
fun of(store: Store): Set<String> = 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<String>, offline: Boolean = false): Map<String, Ids> {
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>): 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<String>): Map<String, Ids> {
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<String, Ids> {
val rows = JSONObject(json).getJSONObject("results").getJSONArray("bindings")
val out = HashMap<String, Triple<MutableSet<String>, MutableSet<String>, MutableSet<String>>>()
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/<slug>" (or "movie/<slug>"); 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<String>, offline: Boolean = false): Map<String, String> {
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<String, String> {
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()
}
}
}
@@ -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
@@ -64,7 +64,7 @@ internal fun recompRows(): List<RecompRow> = 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<String, Boolean>? = 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
}