mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 13:55:58 +00:00
fix: SteamGridDB lookups no longer stick as "no match" after a failure; add a search to the art chooser (#876)
This commit is contained in:
1 parent
7c73adb3aa
commit
8874276458
6 files changed
+340
-26
No files matched your search
@@ -36,6 +36,10 @@ object AddedGameArt {
|
||||
|
||||
class Option(val group: String, val thumb: String, val full: String)
|
||||
|
||||
class Choices(val options: List<Option>, val sgdb: SteamGridDb.Status)
|
||||
|
||||
class Found<T>(val items: List<T>, val status: SteamGridDb.Status)
|
||||
|
||||
private val CHOSEN = Regex("""chosen-(\w+)\.(\w+)""")
|
||||
|
||||
private fun chosen(cache: File, slot: Slot): File? =
|
||||
@@ -108,7 +112,7 @@ object AddedGameArt {
|
||||
dir.listFiles { f -> f.isFile && f.extension.lowercase() in CHOOSABLE }?.sortedBy { it.name.lowercase() }.orEmpty()
|
||||
}.take(12)
|
||||
|
||||
fun options(context: Context, game: AddedGames.Game, slot: Slot): List<Option> {
|
||||
fun choices(context: Context, game: AddedGames.Game, slot: Slot): Choices {
|
||||
val out = ArrayList<Option>()
|
||||
folderImages(game.folder).forEach { out.add(Option(FOLDER, it.path, it.path)) }
|
||||
val cache = cacheDir(context, game)
|
||||
@@ -118,16 +122,42 @@ object AddedGameArt {
|
||||
val url = "$CDN$steamId/$remote".takeIf { exists(it) } ?: steamAssetUrl(steamId, remote)
|
||||
if (url != null) out.add(Option(STEAM, url, url))
|
||||
}
|
||||
var status = SteamGridDb.Status.OK
|
||||
val key = SteamGridDb.key(context)
|
||||
if (key.isNotEmpty()) {
|
||||
if (key.isEmpty()) {
|
||||
status = SteamGridDb.Status.NO_KEY
|
||||
} else {
|
||||
cache.mkdirs()
|
||||
val gridId = remembered(File(cache, "sgdb-id")) {
|
||||
runCatching { SteamGridDb.gameId(key, steamId?.toIntOrNull(), game.name) }.getOrNull()?.toString()
|
||||
}?.toIntOrNull()
|
||||
if (gridId != null) runCatching { SteamGridDb.images(key, gridId, slot, if (slot == Slot.ICON) 3 else 5) }.getOrNull()
|
||||
?.forEach { (thumb, full) -> out.add(Option(SGDB, thumb, full)) }
|
||||
try {
|
||||
val gridId = remembered(File(cache, "sgdb-id"), SteamGridDb.keyChangedAt(context), retryMiss = true) {
|
||||
SteamGridDb.gameId(key, steamId?.toIntOrNull(), game.name)?.toString()
|
||||
}?.toIntOrNull()
|
||||
if (gridId == null) status = SteamGridDb.Status.NO_GAME
|
||||
else SteamGridDb.images(key, gridId, slot, if (slot == Slot.ICON) 3 else 5)
|
||||
.forEach { (thumb, full) -> out.add(Option(SGDB, thumb, full)) }
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "${game.name}: SteamGridDB failed (${e.javaClass.simpleName})")
|
||||
status = (e as? SteamGridDb.Failed)?.status ?: SteamGridDb.Status.SERVER
|
||||
}
|
||||
}
|
||||
return Choices(out, status)
|
||||
}
|
||||
|
||||
fun searchGames(context: Context, term: String): Found<SteamGridDb.Game> = sgdb(context) { SteamGridDb.search(it, term) }
|
||||
|
||||
fun gameImages(context: Context, id: Int, slot: Slot, page: Int): Found<Option> = sgdb(context) { key ->
|
||||
SteamGridDb.page(key, id, slot, page).map { (thumb, full) -> Option(SGDB, thumb, full) }
|
||||
}
|
||||
|
||||
private fun <T> sgdb(context: Context, call: (String) -> List<T>): Found<T> {
|
||||
val key = SteamGridDb.key(context)
|
||||
if (key.isEmpty()) return Found(emptyList(), SteamGridDb.Status.NO_KEY)
|
||||
return try {
|
||||
Found(call(key), SteamGridDb.Status.OK)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "SteamGridDB: ${e.javaClass.simpleName}")
|
||||
Found(emptyList(), (e as? SteamGridDb.Failed)?.status ?: SteamGridDb.Status.SERVER)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun choose(context: Context, game: AddedGames.Game, slot: Slot, option: Option): Boolean {
|
||||
@@ -180,6 +210,8 @@ object AddedGameArt {
|
||||
fun fetchMissing(context: Context, games: List<AddedGames.Game>): Boolean {
|
||||
if (!SessionPrefs.addedGamesArt(context)) return false
|
||||
val sgdbKey = SteamGridDb.key(context)
|
||||
val keyChangedAt = SteamGridDb.keyChangedAt(context)
|
||||
var sgdbDown = false
|
||||
var changed = false
|
||||
for (game in games) {
|
||||
if (local(game).portrait != null) continue
|
||||
@@ -192,11 +224,24 @@ object AddedGameArt {
|
||||
val appId = match.appId?.takeIf { match.certainty == SteamMatch.Certainty.FILES }
|
||||
val id = match.appId?.toString()
|
||||
if (id != null && download(id, cache)) changed = true
|
||||
if (File(cache, "p.jpg").isFile || sgdbKey.isEmpty()) continue
|
||||
val gridId = remembered(File(cache, "sgdb-id")) {
|
||||
runCatching { SteamGridDb.gameId(sgdbKey, appId ?: id?.toIntOrNull(), game.name) }.getOrNull()?.toString()
|
||||
}?.toIntOrNull() ?: continue
|
||||
if (runCatching { SteamGridDb.download(sgdbKey, gridId, cache) }.getOrDefault(false)) changed = true
|
||||
if (File(cache, "p.jpg").isFile || sgdbKey.isEmpty() || sgdbDown) continue
|
||||
val stored: String? = try {
|
||||
remembered(File(cache, "sgdb-id"), keyChangedAt) {
|
||||
SteamGridDb.gameId(sgdbKey, appId ?: id?.toIntOrNull(), game.name)?.toString()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "${game.name}: SteamGridDB lookup failed (${e.javaClass.simpleName}); not asking again this pass")
|
||||
sgdbDown = true
|
||||
null
|
||||
}
|
||||
val gridId = stored?.toIntOrNull() ?: continue
|
||||
val grabbed = try {
|
||||
SteamGridDb.download(sgdbKey, gridId, cache)
|
||||
} catch (e: Exception) {
|
||||
sgdbDown = true
|
||||
false
|
||||
}
|
||||
if (grabbed) changed = true
|
||||
}
|
||||
return changed
|
||||
}
|
||||
@@ -207,11 +252,12 @@ object AddedGameArt {
|
||||
return match
|
||||
}
|
||||
|
||||
private fun remembered(marker: File, find: () -> String?): String? {
|
||||
internal fun remembered(marker: File, notBefore: Long = 0L, retryMiss: Boolean = false, find: () -> String?): String? {
|
||||
if (marker.isFile) {
|
||||
val value = marker.readText().trim()
|
||||
if (value != "none") return value
|
||||
if (System.currentTimeMillis() - marker.lastModified() < RETRY_AFTER_MS) return null
|
||||
val at = marker.lastModified()
|
||||
if (!retryMiss && at >= notBefore && System.currentTimeMillis() - at < RETRY_AFTER_MS) return null
|
||||
}
|
||||
val found = find()
|
||||
marker.writeText(found ?: "none")
|
||||
|
||||
@@ -16,6 +16,12 @@ object SteamGridDb {
|
||||
private const val API = "https://www.steamgriddb.com/api/v2"
|
||||
private const val QUERY = "nsfw=false&humor=false"
|
||||
|
||||
enum class Status { OK, NO_KEY, BAD_KEY, LIMIT, OFFLINE, SERVER, NO_GAME }
|
||||
|
||||
class Failed(val status: Status) : Exception(status.name)
|
||||
|
||||
class Game(val id: Int, val name: String, val verified: Boolean)
|
||||
|
||||
@VisibleForTesting
|
||||
@Volatile
|
||||
internal var keys: CredentialCipher.KeyProvider = CredentialCipher.Keystore
|
||||
@@ -30,6 +36,8 @@ object SteamGridDb {
|
||||
|
||||
fun key(context: Context): String = pick(userKey(context), builtInKey())
|
||||
|
||||
fun keyChangedAt(context: Context): Long = keyFile(context).lastModified()
|
||||
|
||||
@Synchronized
|
||||
fun userKey(context: Context): String {
|
||||
val f = keyFile(context)
|
||||
@@ -97,17 +105,37 @@ object SteamGridDb {
|
||||
return got
|
||||
}
|
||||
|
||||
fun images(key: String, id: Int, slot: AddedGameArt.Slot, limit: Int): List<Pair<String, String>> {
|
||||
val path = when (slot) {
|
||||
fun search(key: String, term: String): List<Game> {
|
||||
val q = term.trim()
|
||||
if (q.isEmpty()) return emptyList()
|
||||
val enc = URLEncoder.encode(q, "UTF-8").replace("+", "%20")
|
||||
val data = json(key, "$API/search/autocomplete/$enc")?.optJSONArray("data") ?: return emptyList()
|
||||
return games(data)
|
||||
}
|
||||
|
||||
internal fun games(data: JSONArray): List<Game> =
|
||||
(0 until data.length()).mapNotNull { data.optJSONObject(it) }
|
||||
.filter { it.optInt("id") > 0 && it.optString("name").isNotEmpty() }
|
||||
.map { Game(it.optInt("id"), it.optString("name"), it.optBoolean("verified")) }
|
||||
|
||||
internal fun path(id: Int, slot: AddedGameArt.Slot, page: Int): String {
|
||||
val base = when (slot) {
|
||||
AddedGameArt.Slot.COVER -> "grids/game/$id?dimensions=600x900&$QUERY"
|
||||
AddedGameArt.Slot.BACKGROUND -> "heroes/game/$id?$QUERY"
|
||||
AddedGameArt.Slot.LOGO -> "logos/game/$id?$QUERY"
|
||||
AddedGameArt.Slot.ICON -> "icons/game/$id?$QUERY"
|
||||
}
|
||||
val items = json(key, "$API/$path")?.optJSONArray("data") ?: return emptyList()
|
||||
return ranked(items, pngOnly = slot == AddedGameArt.Slot.LOGO || slot == AddedGameArt.Slot.ICON).take(limit)
|
||||
return if (page > 0) "$base&page=$page" else base
|
||||
}
|
||||
|
||||
fun page(key: String, id: Int, slot: AddedGameArt.Slot, page: Int): List<Pair<String, String>> {
|
||||
val items = json(key, "$API/${path(id, slot, page)}")?.optJSONArray("data") ?: return emptyList()
|
||||
return ranked(items, pngOnly = slot == AddedGameArt.Slot.LOGO || slot == AddedGameArt.Slot.ICON)
|
||||
}
|
||||
|
||||
fun images(key: String, id: Int, slot: AddedGameArt.Slot, limit: Int): List<Pair<String, String>> =
|
||||
page(key, id, slot, 0).take(limit)
|
||||
|
||||
internal fun ranked(items: JSONArray, pngOnly: Boolean): List<Pair<String, String>> =
|
||||
(0 until items.length()).map { items.getJSONObject(it) }
|
||||
.filter { it.optString("url").startsWith("https://") && (!pngOnly || it.optString("mime") == "image/png" || it.optString("url").endsWith(".png", true)) }
|
||||
@@ -119,6 +147,13 @@ object SteamGridDb {
|
||||
.filter { it.optString("url").startsWith("https://") && (!pngOnly || it.optString("mime") == "image/png" || it.optString("url").endsWith(".png", true)) }
|
||||
.maxByOrNull { it.optInt("score", 0) }?.optString("url")
|
||||
|
||||
internal fun failure(code: Int): Status? = when {
|
||||
code == 401 || code == 403 -> Status.BAD_KEY
|
||||
code == 429 -> Status.LIMIT
|
||||
code >= 500 -> Status.SERVER
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun json(key: String, url: String): JSONObject? {
|
||||
val c = URL(url).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 10_000
|
||||
@@ -126,8 +161,19 @@ object SteamGridDb {
|
||||
c.setRequestProperty("User-Agent", "DroidDeck-launcher")
|
||||
c.setRequestProperty("Authorization", "Bearer $key")
|
||||
return try {
|
||||
if (c.responseCode != 200) { Log.w(TAG, "${URL(url).path}: HTTP ${c.responseCode}"); null }
|
||||
else JSONObject(c.inputStream.use { it.readBytes() }.toString(Charsets.UTF_8)).takeIf { it.optBoolean("success", true) }
|
||||
val code = c.responseCode
|
||||
if (code == 200) {
|
||||
JSONObject(c.inputStream.use { it.readBytes() }.toString(Charsets.UTF_8)).takeIf { it.optBoolean("success", true) }
|
||||
} else {
|
||||
Log.w(TAG, "${URL(url).path}: HTTP $code")
|
||||
failure(code)?.let { throw Failed(it) }
|
||||
null
|
||||
}
|
||||
} catch (e: Failed) {
|
||||
throw e
|
||||
} catch (e: java.io.IOException) {
|
||||
Log.w(TAG, "${URL(url).path}: ${e.javaClass.simpleName}")
|
||||
throw Failed(Status.OFFLINE)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "${URL(url).path}: ${e.javaClass.simpleName}"); null
|
||||
} finally {
|
||||
|
||||
Reference in new issue
Block a user