From 583f34fc55276446b6d18daca30021d8f849d2e7 Mon Sep 17 00:00:00 2001 From: K11MCH1 <81425424+K11MCH1@users.noreply.github.com> Date: Sun, 1 Nov 2026 02:36:43 +0900 Subject: [PATCH] fix: stop importing games as Spacewar (480) and follow a changed Steam app id (#1896) --- .../launcher/frontend/AddedGameArt.kt | 42 ++++++++- .../launcher/frontend/GameIdentifier.kt | 8 +- .../droiddeck/launcher/frontend/SteamMatch.kt | 6 +- .../launcher/frontend/AddedGameArtFillTest.kt | 92 +++++++++++++++++++ .../frontend/AddedGameArtLookupTest.kt | 23 +++++ .../launcher/frontend/GameIdentifierTest.kt | 45 ++++++++- docs/development/steam-game-imports.md | 11 ++- .../usr/local/bin/droiddeck-steam-games | 32 ++++--- tools/tests/test_steam_games.py | 70 ++++++++++++++ 9 files changed, 303 insertions(+), 26 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt index 28eb1bf723..bad61e6023 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt @@ -287,14 +287,17 @@ object AddedGameArt { var sgdbDown = false var changed = false for (game in games) { + if (forgetOtherAppsArt(context, game)) changed = true + val cache = cacheDir(context, game) val start = missing(context, game) + val again = refetch(cache) intersect start + if (again.isEmpty()) File(cache, REFETCH).delete() val full = Slot.COVER in start - val allowed = if (full) Slot.values().toSet() else EXTRAS + val allowed = if (full) Slot.values().toSet() else EXTRAS + again var need = start intersect allowed if (need.isEmpty() || (need == setOf(Slot.ICON) && sgdbKey.isEmpty())) continue - val cache = cacheDir(context, game) val tried = File(cache, EXTRAS_TRIED) - if (!full && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue + if (!full && again.isEmpty() && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue cache.mkdirs() if (Slot.LOGO in need && game.source != Library.ADDED && runCatching { sources.storeLogo(game) }.getOrDefault(false)) { changed = true @@ -324,11 +327,42 @@ object AddedGameArt { asked = false } } - if ((missing(context, game) intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("") + val left = missing(context, game) + if (again.isNotEmpty()) keepRefetch(cache, again intersect left) + if ((left intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("") } return changed } + internal const val REFETCH = "refetch" + + private fun refetch(cache: File): Set = + runCatching { File(cache, REFETCH).readText() }.getOrDefault("").split(',').mapNotNull { key -> Slot.values().firstOrNull { it.key == key } }.toSet() + + private fun keepRefetch(cache: File, slots: Set) { + if (slots.isEmpty()) File(cache, REFETCH).delete() else File(cache, REFETCH).writeText(slots.joinToString(",") { it.key }) + } + + internal fun forgetOtherAppsArt(context: Context, game: AddedGames.Game): Boolean { + val cache = cacheDir(context, game) + val recorded = SteamMatch.get(context, game.folder.path)?.takeIf { it.appId != null } + val legacy = runCatching { File(cache, "steam-appid").readText().trim().toInt() }.getOrNull()?.takeIf { it > 0 } + val before = recorded?.appId ?: legacy ?: return false + val identity = runCatching { GameIdentifier.identify(game.exe) }.getOrNull() + val now = identity?.appId + val fromFiles = recorded?.certainty == SteamMatch.Certainty.FILES || before == GameIdentifier.SPACEWAR + if (now == before || (now == null && !fromFiles)) return false + SteamMatch.put(context, game.folder.path, + if (identity != null && now != null) SteamMatch.Match(now, SteamMatch.Certainty.FILES, identity.source.name.lowercase(), System.currentTimeMillis()) + else SteamMatch.Match(null, SteamMatch.Certainty.NONE, "", 0)) + val dropped = Slot.values().filter { File(cache, SteamGridDb.cacheName(it)).delete() }.toSet() + Slot.values().forEach { File(cache, SteamGridDb.cacheName(it) + ".src").delete() } + listOf("sgdb-id", "steam-appid", EXTRAS_TRIED).forEach { File(cache, it).delete() } + keepRefetch(cache, refetch(cache) + dropped) + Log.i(TAG, "${game.name}: its files no longer name Steam app $before; its art is fetched again") + return dropped.isNotEmpty() + } + internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match { if (game.source == Store.BATTLENET.id) { val id = game.storeId?.let(BattleNet::title)?.steam diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameIdentifier.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameIdentifier.kt index c8faf20e71..90735d1e54 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/GameIdentifier.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameIdentifier.kt @@ -5,6 +5,7 @@ import java.io.File object GameIdentifier { private const val MAX_PARENT_DEPTH = 6 + internal const val SPACEWAR = 480 enum class Source { STEAM_APPID_TXT, STEAM_MANIFEST_ACF, STEAM_EMU_INI, GOG_INFO, PE_VERSION, FILENAME, NONE } enum class Confidence { HIGH, MEDIUM, LOW } @@ -92,7 +93,7 @@ object GameIdentifier { for (candidate in arrayOf(File(dir, "steam_appid.txt"), File(dir, "steam_settings/steam_appid.txt"))) { val id = readSmallTextFile(candidate)?.removePrefix("\uFEFF")?.trim() ?.takeWhile { it.isDigit() }?.toIntOrNull() - if (id != null && id > 0) return id + if (id != null && id > 0 && id != SPACEWAR) return id } return null } @@ -111,7 +112,7 @@ object GameIdentifier { for (f in candidates) { val text = readSmallTextFile(f) ?: continue val id = re.find(text)?.groupValues?.getOrNull(1)?.toIntOrNull() - if (id != null && id > 0) return id + if (id != null && id > 0 && id != SPACEWAR) return id } return null } @@ -133,7 +134,8 @@ object GameIdentifier { val match = manifests.firstOrNull { m -> val text = readSmallTextFile(m) ?: return@firstOrNull false val installdir = vdfValue(text, "installdir") - gameFolder != null && installdir != null && installdir.equals(gameFolder, ignoreCase = true) + gameFolder != null && installdir != null && installdir.equals(gameFolder, ignoreCase = true) && + vdfValue(text, "appid")?.toIntOrNull() != SPACEWAR } ?: return null val text = readSmallTextFile(match) ?: return null diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SteamMatch.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SteamMatch.kt index c0c83676dc..8371288e2d 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/SteamMatch.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SteamMatch.kt @@ -45,15 +45,15 @@ object SteamMatch { identity?.appId?.let { id -> return Match(id, Certainty.FILES, identity.source.name.lowercase(), now).also { put(context, key, it) } } - val known = get(context, key) + val known = get(context, key)?.takeUnless { it.appId == GameIdentifier.SPACEWAR } if (known != null && known.certainty == Certainty.NAME) return known if (known != null && known.certainty == Certainty.NONE && now - known.checkedAt < RETRY_AFTER_MS) return known - legacy?.takeIf { it.isFile }?.let { runCatching { it.readText().trim().toInt() }.getOrNull() }?.takeIf { it > 0 }?.let { id -> + legacy?.takeIf { it.isFile }?.let { runCatching { it.readText().trim().toInt() }.getOrNull() }?.takeIf { it > 0 && it != GameIdentifier.SPACEWAR }?.let { id -> return Match(id, Certainty.NAME, "store search", now).also { put(context, key, it) } } if (search == null) return known?.takeIf { it.certainty != Certainty.FILES } ?: Match(null, Certainty.NONE, "", 0) val id = runCatching { search(name) }.getOrNull() - val match = if (id != null && id > 0) Match(id, Certainty.NAME, "store search", now) else Match(null, Certainty.NONE, "", now) + val match = if (id != null && id > 0 && id != GameIdentifier.SPACEWAR) Match(id, Certainty.NAME, "store search", now) else Match(null, Certainty.NONE, "", now) put(context, key, match) return match } diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGameArtFillTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGameArtFillTest.kt index 473c43922a..b9b223d657 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGameArtFillTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGameArtFillTest.kt @@ -154,6 +154,98 @@ class AddedGameArtFillTest { assertFalse(File(AddedGameArt.cacheDir(app, second), AddedGameArt.EXTRAS_TRIED).exists()) } + private fun steamFrom(asked: MutableList, bytes: Byte, search: Int? = null, slotsAsked: MutableList> = ArrayList()) = AddedGameArt.Sources( + storeLogo = { false }, + steamSearch = { if (search == null) fail("searched although the game names its appid"); search }, + steam = { id, cache, slots -> + asked += id + slotsAsked += slots + slots.forEach { File(cache, steamNames.getValue(it)).writeBytes(byteArrayOf(bytes)) } + slots.isNotEmpty() + }, + sgdbGame = { _, _, _ -> null }, + sgdb = { _, _, _, _ -> false }, + ) + + @Test fun artOfTheAppTheFilesNamedBeforeIsFetchedAgain() { + val g = game("Peak", 0x8100000AL, cover = false) + File(g.folder, "steam_appid.txt").writeText("1029210") + val asked = ArrayList() + assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 1))) + File(g.folder, "steam_appid.txt").writeText("3527290") + assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 2))) + assertEquals(listOf("1029210", "3527290"), asked) + assertArrayEquals(byteArrayOf(2), File(AddedGameArt.cacheDir(app, g), "p.jpg").readBytes()) + assertFalse(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 3))) + assertEquals(2, asked.size) + } + + @Test fun aPictureTheUserChoseOutlivesTheChange() { + val g = game("Peak", 0x8100000BL, cover = false) + File(g.folder, "steam_appid.txt").writeText("1029210") + AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(ArrayList(), 1)) + val picked = File(tmp.root, "mine.jpg").apply { writeBytes(byteArrayOf(7)) } + assertTrue(AddedGameArt.store(AddedGameArt.cacheDir(app, g), Slot.COVER, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path))) + File(g.folder, "steam_appid.txt").writeText("3527290") + val asked = ArrayList() + val slots = ArrayList>() + AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 2, slotsAsked = slots)) + assertArrayEquals(byteArrayOf(7), AddedGameArt.resolve(app, g).portrait!!.readBytes()) + assertEquals(listOf("3527290"), asked) + assertEquals(listOf(setOf(Slot.WIDE, Slot.BACKGROUND, Slot.LOGO)), slots) + val cache = AddedGameArt.cacheDir(app, g) + assertArrayEquals(byteArrayOf(2), File(cache, "header.jpg").readBytes()) + assertArrayEquals(byteArrayOf(2), File(cache, "hero.jpg").readBytes()) + assertFalse(File(cache, AddedGameArt.REFETCH).exists()) + } + + private fun olderBuildsArt(g: AddedGames.Game, marker: String): File = AddedGameArt.cacheDir(app, g).apply { + mkdirs() + File(this, "steam-appid").writeText(marker) + steamNames.values.forEach { File(this, it).writeBytes(byteArrayOf(1)) } + } + + @Test fun anOlderBuildsSpacewarMarkerGoesWithItsArt() { + val g = game("Peak", 0x8100000DL, cover = false) + File(g.folder, "steam_appid.txt").writeText("480") + val cache = olderBuildsArt(g, "480") + val asked = ArrayList() + assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 2, search = 3527290))) + assertEquals(listOf("3527290"), asked) + assertArrayEquals(byteArrayOf(2), File(cache, "p.jpg").readBytes()) + assertFalse(File(cache, "steam-appid").exists()) + } + + @Test fun anOlderBuildsMatchStaysWhileTheFilesNameNoApp() { + val g = game("Hades", 0x8100000EL, cover = false) + File(g.folder, "steam_appid.txt").delete() + val cache = olderBuildsArt(g, "1145360") + assertFalse(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(ArrayList(), 2))) + assertEquals("1145360", File(cache, "steam-appid").readText()) + assertArrayEquals(byteArrayOf(1), File(cache, "p.jpg").readBytes()) + } + + @Test fun anOlderBuildsMatchGivesWayToTheAppTheFilesName() { + val g = game("Peak", 0x8100000FL, cover = false) + File(g.folder, "steam_appid.txt").writeText("3527290") + val cache = olderBuildsArt(g, "1029210") + val asked = ArrayList() + assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 2))) + assertEquals(listOf("3527290"), asked) + assertArrayEquals(byteArrayOf(2), File(cache, "p.jpg").readBytes()) + assertFalse(File(cache, "steam-appid").exists()) + } + + @Test fun filesThatStopNamingAnAppFallBackToTheGamesName() { + val g = game("Peak", 0x8100000CL, cover = false) + File(g.folder, "steam_appid.txt").writeText("1029210") + val asked = ArrayList() + AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 1)) + File(g.folder, "steam_appid.txt").writeText("480") + assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "", steamFrom(asked, 2, search = 3527290))) + assertEquals(listOf("1029210", "3527290"), asked) + } + @Test fun nothingIsFetchedWhenArtIsOff() { SessionPrefs.setAddedGamesArt(app, false) val calls = Calls() diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGameArtLookupTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGameArtLookupTest.kt index 095cf9a5c5..9a949bad2a 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGameArtLookupTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGameArtLookupTest.kt @@ -66,6 +66,29 @@ class AddedGameArtLookupTest { assertEquals(SteamMatch.Certainty.NAME, match.certainty) } + @Test fun anEarlierBuildsSpacewarLookupIsNotAMatch() { + val dir = tmp.newFolder("Peak") + val exe = File(dir, "PEAK.exe").apply { writeText("x") } + val legacy = File(tmp.newFolder(), "steam-appid").apply { writeText("480") } + assertEquals(3527290, SteamMatch.resolve(app, dir.path, exe, "PEAK", legacy = legacy) { 3527290 }.appId) + } + + @Test fun aSavedSpacewarMatchIsNotAMatch() { + val dir = tmp.newFolder("Peak") + val exe = File(dir, "PEAK.exe").apply { writeText("x") } + SteamMatch.put(app, dir.path, SteamMatch.Match(480, SteamMatch.Certainty.NAME, "store search", System.currentTimeMillis())) + assertNull(SteamMatch.resolve(app, dir.path, exe, "PEAK").appId) + assertEquals(3527290, SteamMatch.resolve(app, dir.path, exe, "PEAK") { 3527290 }.appId) + } + + @Test fun aStoreSearchAnsweringSpacewarIsNoMatch() { + val dir = tmp.newFolder("Spacewar Fan Remake") + val exe = File(dir, "game.exe").apply { writeText("x") } + val match = SteamMatch.resolve(app, dir.path, exe, "Spacewar Fan Remake") { 480 } + assertNull(match.appId) + assertEquals(SteamMatch.Certainty.NONE, match.certainty) + } + @Test fun aStoreResultIsTakenOnlyWhenItsNameMatches() { assertNull(AddedGameArt.pickStoreResult("My Obscure Game", listOf("10" to "Totally Different", "11" to "Another One"))) assertEquals("20", AddedGameArt.pickStoreResult("Hades", listOf("19" to "Hades II Soundtrack Bundle Extra", "20" to "Hades"))) diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/GameIdentifierTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameIdentifierTest.kt index d67170d1e7..1bd80fea4b 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/GameIdentifierTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameIdentifierTest.kt @@ -31,8 +31,25 @@ class GameIdentifierTest { fun steamAppIdTxt_inSteamSettingsSubdir_isFound() { val dir = tmp.newFolder("Game") File(dir, "steam_settings").mkdirs() - File(dir, "steam_settings/steam_appid.txt").writeText("480") - assertEquals(480, GameIdentifier.identify(exeIn(dir)).appId) + File(dir, "steam_settings/steam_appid.txt").writeText("3527290") + assertEquals(3527290, GameIdentifier.identify(exeIn(dir)).appId) + } + + @Test + fun spacewarAppId_namesNoGame() { + val dir = tmp.newFolder("PEAK") + File(dir, "steam_appid.txt").writeText("480") + File(dir, "steam_emu.ini").writeText("[Settings]\nAppId=480\n") + assertNull(GameIdentifier.identify(exeIn(dir)).appId) + } + + @Test + fun spacewarAppId_fallsThroughToTheGamesOwnId() { + val dir = tmp.newFolder("PEAK") + File(dir, "steam_appid.txt").writeText("480") + File(dir, "steam_settings").mkdirs() + File(dir, "steam_settings/steam_appid.txt").writeText("3527290") + assertEquals(3527290, GameIdentifier.identify(exeIn(dir)).appId) } @Test @@ -44,6 +61,30 @@ class GameIdentifierTest { assertEquals(GameIdentifier.Source.STEAM_EMU_INI, id.source) } + @Test + fun spacewarManifest_namesNoGame() { + val steamapps = tmp.newFolder("steamapps") + File(steamapps, "appmanifest_480.acf").writeText(""""AppState" { "appid" "480" "name" "Spacewar" "installdir" "PEAK" }""") + val game = File(steamapps, "common/PEAK").apply { mkdirs() } + File(game, "steam_appid.txt").writeText("3527290") + val id = GameIdentifier.identify(exeIn(game, "PEAK.exe")) + assertEquals(3527290, id.appId) + assertEquals(GameIdentifier.Source.STEAM_APPID_TXT, id.source) + assertTrue(id.name != "Spacewar") + } + + @Test + fun spacewarManifest_leavesTheGamesOwnManifestForTheSameFolder() { + val steamapps = tmp.newFolder("steamapps") + File(steamapps, "appmanifest_480.acf").writeText(""""AppState" { "appid" "480" "name" "Spacewar" "installdir" "PEAK" }""") + File(steamapps, "appmanifest_3527290.acf").writeText(""""AppState" { "appid" "3527290" "name" "PEAK" "installdir" "PEAK" }""") + val game = File(steamapps, "common/PEAK").apply { mkdirs() } + val id = GameIdentifier.identify(exeIn(game, "PEAK.exe")) + assertEquals(3527290, id.appId) + assertEquals("PEAK", id.name) + assertEquals(GameIdentifier.Source.STEAM_MANIFEST_ACF, id.source) + } + @Test fun steamManifestAcf_matchedByInstalldir_givesAppIdAndName() { val steamapps = tmp.newFolder("steamapps") diff --git a/docs/development/steam-game-imports.md b/docs/development/steam-game-imports.md index 78ae2cc110..571a208c1d 100644 --- a/docs/development/steam-game-imports.md +++ b/docs/development/steam-game-imports.md @@ -7,7 +7,9 @@ importer as Added Games. Existing Steam manifests are preserved. `droiddeck-steam-games watch` runs beside the client. It identifies a game by an existing manifest's install directory, a `steam_appid.txt` beside the game or selected executable, or a unique normalized title from Steam's store search with an explicit -country. Matching also accepts the terminal Windows Edition and INTERGRADE suffixes; +country. A `steam_appid.txt` naming 480 (Spacewar, the Steamworks SDK sample that Steam +emulators and multiplayer fixes use in place of the game) identifies nothing; the +launcher's artwork matching ignores it too. Matching also accepts the terminal Windows Edition and INTERGRADE suffixes; multiple matches still remain unresolved. Artwork's fuzzy matching is deliberately not used for identity. Ambiguous or unresolved titles remain non-Steam games. @@ -42,6 +44,13 @@ the earlier importer are migrated, with the matching source symlink still presen registration fails, the game remains a shortcut. Once Steam takes over an install, manage it in Steam; forgetting an Added Games folder only removes its shortcuts. +An import is undone (its symlink and manifest, never the folder) when the folder was +imported as Spacewar, or when a snapshot of the folder's current files names another app. +The folder is then imported as that app if the account owns it, else it is a shortcut +again. A failed title lookup undoes nothing. The launcher likewise drops artwork it +fetched for the app the files named before and fetches it again; pictures the user chose +are kept. + The account's `.droiddeck-routes.json` maps shortcut IDs to real Steam app IDs so the Android launcher uses the same title and Proton prefix as Steam. Other accounts do not inherit those routes. Managed shortcuts are replaced; user-created shortcuts and diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games index 775980a0c5..ca9c1a1cca 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games @@ -20,6 +20,7 @@ LIBRARY = "/mnt/droiddeck-sd" LEGACY_LIBRARY = "/mnt/bannerlator-sd" PARKED = ".droiddeck-parked" BASE_ID = 76561197960265728 +SPACEWAR = 480 def read_json(path, default): @@ -86,14 +87,14 @@ def identify(game): folder = Path(game["folder"]) steamapps = folder.parent.parent for library in ([steamapps] if folder.parent.name == "common" and steamapps.name == "steamapps" else []) + [folder.parent / WINNATIVE]: - matches = manifest_ids(library, folder.name) + matches = [appid for appid in manifest_ids(library, folder.name) if appid != SPACEWAR] if matches: return matches[0] if len(matches) == 1 else None ids = set() for parent in {folder, Path(game["exe"]).parent}: try: appid = int((parent / "steam_appid.txt").read_text().strip()) - if 0 < appid < 0x80000000: + if 0 < appid < 0x80000000 and appid != SPACEWAR: ids.add(appid) except (OSError, ValueError): pass @@ -107,7 +108,7 @@ def identify(game): ids = {int(item["id"]) for item in items if key(item.get("name", "")) == key(game["name"]) and key(game["name"])} if ids: - return next(iter(ids)) if len(ids) == 1 else None + return next(iter(ids)) if len(ids) == 1 and SPACEWAR not in ids else None return None except (OSError, ValueError, KeyError): return None @@ -423,20 +424,20 @@ def seed_install(steam_root, game, appid): return True -def release(steam_root, game): - """Undoes an import made before store games were skipped. Only our symlink and manifest go; - the store's folder stays where it is.""" +def release(steam_root, game, stale, reason): + """Undoes the imports of the game's folder as the Steam apps [stale] picks. Only our symlink and + manifest go; the folder stays where it is.""" steamapps = Path(steam_root) / "steamapps" sources = {game.get("folder", ""), legacy_path(game.get("folder", ""))} for target in sorted((steamapps / "common").glob("DroidDeck-*")): appid = target.name.removeprefix("DroidDeck-") - if not (appid.isdigit() and target.is_symlink() and os.readlink(target) in sources): + if not (appid.isdigit() and target.is_symlink() and os.readlink(target) in sources and stale(int(appid))): continue for manifest in (steamapps / f"appmanifest_{appid}.acf", steamapps / PARKED / f"appmanifest_{appid}.acf"): if manifest.is_file() and ours(manifest, appid): manifest.unlink() target.unlink() - print(f"droiddeck-steam-games: {game.get('name', appid)} came from {game['store']}; it is a shortcut again, not Steam app {appid}") + print(f"droiddeck-steam-games: {game.get('name', appid)} {reason}; it is no longer Steam app {appid}") def route(steam_root, acct, games): @@ -457,7 +458,7 @@ def route(steam_root, acct, games): for game in games: if store_game(game): try: - release(steam_root, game) + release(steam_root, game, lambda old: True, f"came from {game['store']}") except OSError as error: print(f"droiddeck-steam-games: store import not undone ({error})") shortcuts.append(game) @@ -469,9 +470,14 @@ def route(steam_root, acct, games): appid = candidates.get(folder, candidates.get(legacy_path(folder))) stamp = source_stamp(game) recorded = sources.get(folder, sources.get(legacy_path(folder))) - confirmed = (isinstance(appid, int) and 0 < appid < 0x80000000 - and owned.get(str(appid)) is True and stamp is not None - and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:])) + current = stamp is not None and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:]) + named = isinstance(appid, int) and 0 < appid < 0x80000000 and appid != SPACEWAR + try: + release(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid), + "names another Steam app now") + except OSError as error: + print(f"droiddeck-steam-games: earlier import not undone ({error})") + confirmed = named and current and owned.get(str(appid)) is True if confirmed: try: if seed_install(steam_root, game, appid): @@ -480,7 +486,7 @@ def route(steam_root, acct, games): print(f"droiddeck-steam-games: {game.get('name', appid)} stays a shortcut this session: it could not be linked as Steam app {appid}") except OSError as error: print(f"droiddeck-steam-games: import unavailable ({error})") - elif isinstance(appid, int) and 0 < appid < 0x80000000 and seeded(steamapps, game, appid): + elif named and seeded(steamapps, game, appid): routes[str(game["appid"])] = appid continue shortcuts.append(game) diff --git a/tools/tests/test_steam_games.py b/tools/tests/test_steam_games.py index c09d751a95..491284935f 100644 --- a/tools/tests/test_steam_games.py +++ b/tools/tests/test_steam_games.py @@ -391,6 +391,61 @@ class ImportsTest(unittest.TestCase): with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError): self.assertEqual(42, imports.identify(self.game)) + def test_spacewar_appid_names_no_game(self): + (self.folder / 'steam_appid.txt').write_text('480\n') + with patch.object(imports.urllib.request, 'urlopen', side_effect=OSError): + self.assertIsNone(imports.identify(self.game)) + + def import_as(self, appid): + self.assertTrue(imports.seed_install(self.steam, self.game, appid)) + self.assertTrue((self.steam / f'steamapps/appmanifest_{appid}.acf').is_file()) + + def snapshot_names(self, appid, owned): + imports.save_json(self.acct / 'config' / imports.STATE, + dict(account='123', owned={str(appid): owned}, + candidates={str(self.folder): appid}, + sources={str(self.folder): imports.source_stamp(self.game)})) + + def assert_not_imported_as(self, appid): + self.assertFalse((self.steam / f'steamapps/appmanifest_{appid}.acf').exists()) + self.assertFalse(os.path.lexists(self.steam / f'steamapps/common/DroidDeck-{appid}')) + + def test_spacewar_import_is_released_and_never_made_again(self): + self.import_as(480) + self.snapshot_names(480, owned=True) + with patch('builtins.print'): + self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game])) + self.assert_not_imported_as(480) + self.assertEqual(b'game', self.exe.read_bytes()) + + def test_import_follows_the_app_the_files_name_now(self): + self.snapshot() + imports.route(self.steam, self.acct, [self.game]) + self.snapshot_names(43, owned=True) + with patch('builtins.print'): + self.assertEqual(([], {str(self.game['appid']): 43}), imports.route(self.steam, self.acct, [self.game])) + self.assert_not_imported_as(42) + self.assertEqual(self.folder, (self.steam / 'steamapps/common/DroidDeck-43').resolve()) + + def test_unowned_new_appid_leaves_a_shortcut(self): + self.snapshot() + imports.route(self.steam, self.acct, [self.game]) + self.snapshot_names(43, owned=False) + with patch('builtins.print'): + self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game])) + self.assert_not_imported_as(42) + self.assert_not_imported_as(43) + + def test_import_stays_while_the_new_identity_is_unknown(self): + self.snapshot() + imports.route(self.steam, self.acct, [self.game]) + for candidates in ({}, {str(self.folder): 43}): + imports.save_json(self.acct / 'config' / imports.STATE, + dict(account='123', owned={'43': True}, candidates=candidates, + sources={str(self.folder): ['stale']})) + imports.route(self.steam, self.acct, [self.game]) + self.assertTrue((self.steam / 'steamapps/appmanifest_42.acf').is_file()) + def test_manifest_identity_uses_install_directory(self): folder = self.root / 'second/steamapps/common/Custom Name' folder.mkdir(parents=True) @@ -399,6 +454,21 @@ class ImportsTest(unittest.TestCase): with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError): self.assertEqual(42, imports.identify(game)) + def test_a_spacewar_manifest_names_no_game(self): + folder = self.root / 'second/steamapps/common/PEAK' + folder.mkdir(parents=True) + (folder.parent.parent / 'appmanifest_480.acf').write_text('"AppState" { "installdir" "PEAK" }') + (folder / 'steam_appid.txt').write_text('3527290\n') + game = dict(self.game, folder=str(folder), exe=str(folder / 'PEAK.exe')) + with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError): + self.assertEqual(3527290, imports.identify(game)) + + def test_a_store_search_answering_spacewar_names_no_game(self): + with patch.object(imports.urllib.request, 'urlopen') as request: + request.return_value.__enter__.return_value.read.return_value = json.dumps( + {'items': [{'id': 480, 'name': 'Spacewar'}]}).encode() + self.assertIsNone(imports.identify(dict(self.game, name='Spacewar'))) + def test_store_requires_unique_exact_title(self): cases = [([{'id': 42, 'name': 'Example Deluxe'}], None), ([{'id': 42, 'name': 'Example'}, {'id': 43, 'name': 'Example'}], None),