Stores: GOG, Epic Games and Amazon Games libraries, installs and cloud saves (#476)

A Stores section (rail, under Games; Setup › Stores gate) with each store's sign-in,
library, storefront shelves and a download queue. Each store has two tabs, Store and
Library, and Library filters to All or Installed; libraries open from a saved copy
and refresh in the background, with install sizes on every card. Games install to internal storage,
or a card chosen at Install time, and are registered in the Steam client as non-Steam
games, so they launch through Steam and droiddeck-proton from either the front end or
the client.

- Downloads: GOG, Epic and Amazon engines in Rust (app/src/main/rust/stores, built by
  cargo-ndk, nothing compiled in the tree). One adaptive fetch core with a latency
  brake, stalled-host handoff and every CDN a store offers. Per-stage progress,
  pause/resume, two-step cancel that deletes, failed downloads kept for retry, a
  foreground service with Wi-Fi and wake locks and notification controls.
- Games tab: store source chips (Steam, GOG, Epic, Amazon, Custom) and store art.
- Epic: per-launch exchange code from the app and from Steam's Play button,
  "Epic sign-in (EOS)", "Launch offline", and a game's web links opened in Android's
  browser for EOS consent. The EOS overlay crashed games and is left out.
- Cloud saves (GOG, Epic): pulled before launch, pushed after the game or the session
  ends, no upload before a first download, conflicts never overwritten, backups both
  ways.
- Logs: every store line redacted; the engine log goes to daily files.
This commit is contained in:
The412Banner authored and GitHub committed 2026-10-09 11:08:17 -04:00
1 parent fe71084f23
commit e99d5f9505
141 files changed
+25539 -73

No files matched your search

@@ -0,0 +1,68 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLaunch
import java.io.File
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** A store install is one more folder the scan finds, named and aimed by its sidecar. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGamesStoreScanTest {
private val app get() = RuntimeEnvironment.getApplication()
private fun install(store: Store, id: String, title: String, exe: String, launcher: Boolean = false): File {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.installRoot(app), store), StoreInstallRoot.folderName(title, id))
File(folder, exe).apply { parentFile!!.mkdirs(); writeText("game") }
File(folder, "unins000.exe").writeText("uninstaller")
var sidecar = StoreGameSidecar(store, id, title, exe, args = if (launcher) listOf("-EpicPortal") else emptyList())
if (launcher) sidecar = StoreLaunch.writeLauncher(folder, sidecar)
sidecar.write(folder)
return folder
}
@Test fun aStoreGameIsFoundUnderTheInternalRootWithItsSource() {
val folder = install(Store.GOG, "1207658924", "Heroes of Might and Magic 3: Complete", "HOMM3.exe")
val games = AddedGames.scan(app)
val game = games.single { it.folder.absolutePath == folder.absolutePath }
assertEquals("Heroes of Might and Magic 3: Complete", game.name)
assertEquals("HOMM3.exe", game.exe.name)
assertEquals(Store.GOG.id, game.source)
assertEquals("1207658924", game.storeId)
// Inside the runtime's tree the folder needs no bind: its guest path is its path from the tree's root.
assertEquals("/root/Games/Stores/GOG/Heroes of Might and Magic 3 Complete/HOMM3.exe", game.guestExe)
assertEquals("/root/Games/Stores/GOG/Heroes of Might and Magic 3 Complete", game.guestDir)
}
@Test fun theLauncherIsWhatTheShortcutRunsAndTheExeIsWhatItShows() {
val folder = install(Store.EPIC, "abc", "Celeste", "Celeste.exe", launcher = true)
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
assertEquals("Celeste.exe", game.exe.name)
assertTrue(game.guestExe.endsWith("/" + StoreLaunch.LAUNCHER))
assertEquals(Store.EPIC.id, game.source)
}
@Test fun anOlderSidecarsSteamSwitchIsIgnoredEveryInstallIsListed() {
val folder = install(Store.AMAZON, "amzn1.adg.product.x", "Yakuza 0", "Yakuza0.exe")
val file = StoreGameSidecar.file(folder)
file.writeText(file.readText().replaceFirst("{", "{\"addToSteam\": false,"))
assertTrue(AddedGames.scan(app).any { it.folder.absolutePath == folder.absolutePath })
}
@Test fun theListingCarriesTheLauncherAndTheTitle() {
val folder = install(Store.EPIC, "abc", "Celeste", "Celeste.exe", launcher = true)
val games = AddedGames.scan(app).filter { it.folder.absolutePath == folder.absolutePath }
val listing = AddedGames.writeListing(app, games).readText()
assertTrue(listing.contains("\"name\":\"Celeste\""))
assertTrue(listing.contains(StoreLaunch.LAUNCHER))
}
}
@@ -0,0 +1,66 @@
package com.droiddeck.launcher.stores
import com.droiddeck.launcher.stores.CloudPlan.Entry
import com.droiddeck.launcher.stores.CloudPlan.Local
import com.droiddeck.launcher.stores.CloudPlan.Remote
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** The rules that keep a cloud sync from replacing real saves. (Robolectric for org.json.) */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class CloudPlanTest {
@Test fun noUploadBeforeADownloadHasSetTheBaseline() {
val plan = CloudPlan.up(mapOf("slot0.sav" to Local("new")), mapOf("slot0.sav" to Remote("real", 1000)), null)
assertEquals("no-baseline", plan.refused)
assertTrue(plan.transfer.isEmpty())
}
@Test fun theFirstDownloadLetsTheCloudWin() {
val plan = CloudPlan.down(
mapOf("slot0.sav" to Local("fresh-profile"), "only-local.cfg" to Local("x")),
mapOf("slot0.sav" to Remote("real", 1000), "slot1.sav" to Remote("other", 1000)),
null,
)
assertEquals(setOf("slot0.sav", "slot1.sav"), plan.transfer.toSet())
assertTrue(plan.conflicts.isEmpty())
}
@Test fun aFileChangedOnBothSidesIsAConflictEitherWay() {
val base = mapOf("slot0.sav" to Entry(localMd5 = "a", cloudMd5 = "a", cloudModified = 1000))
val local = mapOf("slot0.sav" to Local("b"))
val remote = mapOf("slot0.sav" to Remote("c", 5000))
assertEquals(listOf("slot0.sav"), CloudPlan.down(local, remote, base).conflicts)
assertTrue(CloudPlan.down(local, remote, base).transfer.isEmpty())
assertEquals(listOf("slot0.sav"), CloudPlan.up(local, remote, base).conflicts)
assertTrue(CloudPlan.up(local, remote, base).transfer.isEmpty())
}
@Test fun theSideThatChangedWins() {
val base = mapOf("s" to Entry("a", "a", 1000))
// Only local changed: up sends it, down leaves it.
assertEquals(listOf("s"), CloudPlan.up(mapOf("s" to Local("b")), mapOf("s" to Remote("a", 1000)), base).transfer)
assertTrue(CloudPlan.down(mapOf("s" to Local("b")), mapOf("s" to Remote("a", 1000)), base).transfer.isEmpty())
// Only the cloud changed: down takes it, up leaves it.
assertEquals(listOf("s"), CloudPlan.down(mapOf("s" to Local("a")), mapOf("s" to Remote("c", 9000)), base).transfer)
assertTrue(CloudPlan.up(mapOf("s" to Local("a")), mapOf("s" to Remote("c", 9000)), base).transfer.isEmpty())
// The same bytes on both sides: nothing moves.
assertEquals(listOf("s"), CloudPlan.up(mapOf("s" to Local("c")), mapOf("s" to Remote("c", 9000)), base).same)
}
@Test fun timesAloneDecideWhenTheServiceGivesNoHash() {
val base = mapOf("s" to Entry("a", null, 1000))
assertEquals(listOf("s"), CloudPlan.down(mapOf("s" to Local("a")), mapOf("s" to Remote(null, 60_000)), base).transfer)
// Within two seconds of the baseline: the same cloud copy.
assertTrue(CloudPlan.down(mapOf("s" to Local("a")), mapOf("s" to Remote(null, 2500)), base).transfer.isEmpty())
}
@Test fun theBaselineSurvivesItsJson() {
val b = mapOf("a/b.sav" to Entry("l", "c", 5), "x" to Entry("l2", null, -1))
assertEquals(b, CloudPlan.fromJson(CloudPlan.toJson(b)))
}
}
@@ -0,0 +1,52 @@
package com.droiddeck.launcher.stores
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
/** A store's save-location template, made concrete inside the game's prefix (Bannerlator's cases). */
class CloudSavePathsTest {
private val root = Files.createTempDirectory("cloud").toFile()
private val prefix = File(root, "compatdata/3785150007/pfx").apply { mkdirs() }
private val install = File(root, "Games/Stores/GOG/ELDERBORN").apply { mkdirs() }
private val profile = File(prefix, "drive_c/users/steamuser")
@Test fun gogElderbornLivesInLocalLow() {
val dir = CloudSavePaths.gog("<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN", prefix, install)
assertEquals(File(profile, "AppData/LocalLow/Hyperstrange/ELDERBORN").path, dir!!.path)
}
@Test fun gogTokensAndEnvironmentStyle() {
assertEquals(File(profile, "Saved Games/X").path, CloudSavePaths.gog("<?SAVED_GAMES?>/X", prefix, install)!!.path)
assertEquals(File(profile, "Documents/My Games/Y").path, CloudSavePaths.gog("<?DOCUMENTS?>\\My Games\\Y", prefix, install)!!.path)
assertEquals(File(profile, "AppData/Roaming/Z").path, CloudSavePaths.gog("%APPDATA%/Z", prefix, install)!!.path)
assertEquals(File(install, "saves").path, CloudSavePaths.gog("<?INSTALL?>/saves", prefix, install)!!.path)
assertNull(CloudSavePaths.gog("<?SOMETHING_ELSE?>/x", prefix, install))
assertNull(CloudSavePaths.gog("no/token", prefix, install))
}
@Test fun aPathThatLeavesItsBoundaryIsRefused() {
assertNull(CloudSavePaths.gog("<?SAVED_GAMES?>/../../../../outside", prefix, install))
assertNull(CloudSavePaths.epic("{InstallDir}/../other", prefix, install, "acc", "app"))
}
@Test fun anExistingFolderIsMatchedWhateverItsCase() {
File(profile, "AppData/LocalLow/hyperstrange/elderborn").mkdirs()
val dir = CloudSavePaths.gog("<?APPLICATION_DATA_LOCAL_LOW?>/Hyperstrange/ELDERBORN", prefix, install)
assertEquals(File(profile, "AppData/LocalLow/hyperstrange/elderborn").path, dir!!.path)
}
@Test fun epicTokensAndPlaceholders() {
assertEquals(File(profile, "AppData/Local/Metalstorm/Saved/SaveGames").path,
CloudSavePaths.epic("{AppData}/Metalstorm/Saved/SaveGames", prefix, install, "acc", "app")!!.path)
assertEquals(File(profile, "Saved Games/Studio/acc/app").path,
CloudSavePaths.epic("{UserSavedGames}/Studio/{EpicId}/{AppName}", prefix, install, "acc", "app")!!.path)
assertEquals(File(profile, "Documents/G").path, CloudSavePaths.epic("{UserDir}/G", prefix, install, "acc", "app")!!.path)
assertNull(CloudSavePaths.epic("{Nope}/G", prefix, install, "acc", "app"))
// Epic's folder names are matched by letters and digits alone when that names exactly one.
File(profile, "AppData/Local/My-Game").mkdirs()
assertEquals(File(profile, "AppData/Local/My-Game").path, CloudSavePaths.epic("{AppData}/MyGame", prefix, install, "acc", "app")!!.path)
}
}
@@ -0,0 +1,96 @@
package com.droiddeck.launcher.stores
import java.io.File
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** A sync against a cloud held in memory: the baseline gate, conflicts, backups and the no-prefix deferral. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class CloudSavesTest {
private val app get() = RuntimeEnvironment.getApplication()
private class Memory : CloudTransport {
val files = HashMap<String, Pair<ByteArray, Long>>()
val puts = ArrayList<String>()
override fun list() = files.map { (k, v) -> CloudFile(k, v.second, CloudSaves.md5(v.first)) }
override fun get(file: CloudFile) = files.getValue(file.name)
override fun put(files: Map<String, ByteArray>): Map<String, Long> =
files.mapValues { (k, v) -> puts += k; this.files[k] = v to 99_000L; 99_000L }
}
private fun dir() = File(app.filesDir, "saves-${System.nanoTime()}").apply { mkdirs() }
private val id get() = "g${System.nanoTime()}"
@Test fun anUploadBeforeAnyDownloadIsRefused() {
val dir = dir(); File(dir, "slot0.sav").writeText("fresh profile")
val cloud = Memory().apply { files["slot0.sav"] = "real save".toByteArray() to 1000L }
val r = CloudSaves.upWith(app, Store.GOG, id, dir, cloud, force = false)
assertEquals("skipped", r.result); assertEquals("no-baseline", r.reason)
assertArrayEquals("real save".toByteArray(), cloud.files.getValue("slot0.sav").first)
}
@Test fun afterADownloadALocalChangeGoesUpAndTheCloudCopyIsKeptFirst() {
val game = id; val dir = dir()
val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L }
assertEquals("ok", CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false).result)
assertEquals("v1", File(dir, "slot0.sav").readText())
File(dir, "slot0.sav").writeText("v2 played")
val r = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false)
assertEquals(1, r.files)
assertEquals("v2 played", String(cloud.files.getValue("slot0.sav").first))
val kept = File(app.filesDir, "stores/cloud-backups/gog-$game").listFiles { f -> f.name.startsWith("cloud-") }!!.single()
assertEquals("v1", File(kept, "slot0.sav").readText())
}
@Test fun aFileChangedOnBothSidesIsLeftForTheUser() {
val game = id; val dir = dir()
val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L }
CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false)
File(dir, "slot0.sav").writeText("local v2")
cloud.files["slot0.sav"] = "cloud v2".toByteArray() to 50_000L
val up = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false)
assertEquals(1, up.conflicts)
assertEquals("cloud v2", String(cloud.files.getValue("slot0.sav").first))
assertEquals(listOf("slot0.sav"), CloudSaves.conflicts(app, Store.GOG, game))
// Keep local resolves it.
CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = true)
assertEquals("local v2", String(cloud.files.getValue("slot0.sav").first))
assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty())
}
@Test fun aDirtyMarkStaysUntilAnUploadGoesThroughOrIsSkippedForGood() {
val gameId = "1207664643"
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "ELDERBORN-mark").apply { mkdirs() }
File(folder, "ELDERBORN.exe").writeText("MZ")
StoreGameSidecar(Store.GOG, gameId, "ELDERBORN", "ELDERBORN.exe").write(folder)
// A save location the store gave, but no prefix yet: the upload cannot run, the mark stays.
com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_template_$gameId", "<?SAVED_GAMES?>/ELDERBORN").apply()
CloudSaves.markDirty(app, Store.GOG, gameId)
assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId))
val first = CloudSaves.uploadDirty(app, Store.GOG, gameId, "session-end")!!
assertEquals("no-prefix", first.reason)
assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId))
// Recovery waits while a session runs.
CloudSaves.uploadAllDirty(app, "recovery", running = true)
assertTrue(CloudSaves.dirty(app).contains(Store.GOG to gameId))
// The store has no cloud saves for it: a final skip, the mark goes; a second trigger finds nothing.
com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_template_$gameId", "").apply()
assertEquals("no-cloud-saves", CloudSaves.uploadDirty(app, Store.GOG, gameId, "exit")!!.reason)
assertTrue(CloudSaves.dirty(app).none { it.second == gameId })
assertEquals(null, CloudSaves.uploadDirty(app, Store.GOG, gameId, "session-end"))
}
@Test fun aFirstLaunchWithoutAPrefixIsDeferredNotBlocked() {
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "ELDERBORN").apply { mkdirs() }
File(folder, "ELDERBORN.exe").writeText("MZ")
StoreGameSidecar(Store.GOG, "1207664643", "ELDERBORN", "ELDERBORN.exe").write(folder)
assertEquals("deferred", CloudSaves.downloadOrDefer(app, Store.GOG, "1207664643").result)
}
}
@@ -0,0 +1,28 @@
package com.droiddeck.launcher.stores
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Test
/** The Installed tab draws what its count counts: the installs on disk. */
class InstalledCardsTest {
private fun install(store: Store, id: String, title: String) =
InstalledStoreGame(StoreGameSidecar(store, id, title, "game.exe", cover = "https://img/$id.jpg"), File("/x/$id"))
@Test fun everyInstallIsACardWhetherOrNotTheLibraryHasLoaded() {
val installed = listOf(install(Store.GOG, "1", "DOOM + DOOM II"), install(Store.GOG, "2", "DOOM I Enhanced"), install(Store.EPIC, "e", "DOOMBLADE"))
// Library not loaded: cards from the sidecars.
val bare = installedCards(Store.GOG, installed, emptyList())
assertEquals(listOf("DOOM + DOOM II", "DOOM I Enhanced"), bare.map { it.title })
assertEquals("https://img/1.jpg", bare.first().tallImageUrl)
// Loaded: the library item wins, by id, or by title when the ids differ.
val library = listOf(
CatalogItem(Store.GOG, "1", "DOOM + DOOM II", imageUrl = "wide1", owned = true),
CatalogItem(Store.GOG, "999", "DOOM I Enhanced", imageUrl = "wide2", owned = true),
CatalogItem(Store.GOG, "3", "Not installed", imageUrl = null, owned = true),
)
val joined = installedCards(Store.GOG, installed, library)
assertEquals(listOf("wide1", "wide2"), joined.map { it.imageUrl })
assertEquals(1, installedCards(Store.EPIC, installed, library).size)
}
}
@@ -0,0 +1,31 @@
package com.droiddeck.launcher.stores
import com.droiddeck.launcher.stores.gog.GogStoreCatalog
import org.json.JSONObject
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** Mature means what the store's own ratings or tags say; a title without them stays visible. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class MatureContentTest {
private fun gog(ratings: String, tags: String) = JSONObject("""{"id":"1","title":"T","ratings":[$ratings],"tags":[$tags]}""")
@Test fun gogRatingsAndTagsDecide() {
assertTrue(GogStoreCatalog.isMature(gog("""{"name":"esrbRating","ageRating":"17"}""", "")))
assertTrue(GogStoreCatalog.isMature(gog("""{"name":"gogRating","ageRating":"18"}""", "")))
assertTrue(GogStoreCatalog.isMature(gog("""{"name":"pegiRating","ageRating":"12"}""", """{"name":"NSFW","slug":"nsfw"}""")))
assertFalse(GogStoreCatalog.isMature(gog("""{"name":"esrbRating","ageRating":"13"},{"name":"uskRating","ageRating":"16"}""", """{"name":"Puzzle","slug":"puzzle"}""")))
// No rating data at all: visible.
assertFalse(GogStoreCatalog.isMature(JSONObject("""{"id":"2","title":"U"}""")))
}
@Test fun tagNamesFromAnyStore() {
assertTrue(matureByTags(listOf("Action", "Sexual Content")))
assertFalse(matureByTags(listOf("Action", "FPS", "RELAXING")))
}
}
@@ -0,0 +1,50 @@
package com.droiddeck.launcher.stores
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertNotSame
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** Sizes kept per version, and a refresh that touches only the cards that changed. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class StoreCacheTest {
private val dir = Files.createTempDirectory("sizes").toFile()
@Test fun aSizeIsKeptForItsVersionAndAskedAgainForANewOne() {
val cache = SizeCache.forStore(dir, Store.EPIC)
cache.put("Metalstorm", "1.0.3", 4_400_000_000L)
// Read back from disk by a new instance, as the next app start does.
val again = SizeCache.forStore(dir, Store.EPIC)
assertEquals(4_400_000_000L, again.get("Metalstorm", "1.0.3"))
assertNull(again.get("Metalstorm", "1.0.4"))
assertNull(again.get("Other", "1.0.3"))
}
@Test fun aFileInAnotherFormatIsDiscarded() {
val file = File(dir, "stores/gog/sizes.json").apply { parentFile!!.mkdirs(); writeText("""{"format":0,"sizes":{"1":{"v":"a","b":5}}}""") }
assertNull(SizeCache(file).get("1", "a"))
}
@Test fun aRefreshKeepsTheObjectsOfUnchangedCards() {
val a = CatalogItem(Store.GOG, "1", "A", imageUrl = "x", owned = true)
val b = CatalogItem(Store.GOG, "2", "B", imageUrl = "y", owned = true)
val old = listOf(a, b)
// Nothing changed: the very list shown stays.
assertSame(old, mergeItems(old, listOf(a.copy(), b.copy())))
// One card changed: the other is the same object, the changed one is new.
val merged = mergeItems(old, listOf(a.copy(), b.copy(title = "B2")))
assertSame(a, merged[0])
assertNotSame(b, merged[1])
assertEquals("B2", merged[1].title)
// A first load is the new list as it is.
val fresh = listOf(a)
assertSame(fresh, mergeItems(null, fresh))
}
}
@@ -0,0 +1,127 @@
package com.droiddeck.launcher.stores
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** Under Robolectric for a real org.json; the plain unit-test android.jar stubs it out. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class StoreGameSidecarTest {
private val sample = StoreGameSidecar(
Store.EPIC, "abc123", "Celeste", "Celeste.exe", launcher = ".droiddeck-launch.bat",
args = listOf("-EpicPortal", "-epicusername=\"Some One\""), env = mapOf("FOO" to "bar"),
installVersion = "1.4.0", installedAt = 1700000000L, cover = "https://x/c.jpg",
extra = mapOf("namespace" to "ns"),
)
@Test fun roundTripsThroughJson() {
val back = StoreGameSidecar.parse(sample.toJson().toString())!!
assertEquals(Store.EPIC, back.store)
assertEquals("abc123", back.id)
assertEquals("Celeste", back.title)
assertEquals("Celeste.exe", back.exe)
assertEquals(".droiddeck-launch.bat", back.launcher)
assertEquals(sample.args, back.args)
assertEquals(sample.env, back.env)
assertEquals("1.4.0", back.installVersion)
assertEquals(1700000000L, back.installedAt)
assertEquals("https://x/c.jpg", back.cover)
assertEquals("ns", back.extra["namespace"])
}
@Test fun defaultsWhenFieldsAreAbsent() {
val back = StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"bin\\game.exe","addToSteam":false}""")!!
// An older sidecar's Steam switch is read past, not acted on.
assertEquals("bin/game.exe", back.exe)
assertNull(back.launcher)
assertTrue(back.args.isEmpty())
// No state field = an earlier build's finished install.
assertTrue(back.isInstalled)
}
@Test fun epicLaunchChoicesRoundTripAndDefaultOn() {
val plain = StoreGameSidecar.parse(StoreGameSidecar(Store.EPIC, "m", "Metalstorm", "M.exe").toJson().toString())!!
assertEquals(EpicOptions(eos = true, offline = false), plain.epic)
assertTrue(plain.epic.wantsCode)
val set = StoreGameSidecar(Store.EPIC, "m", "Metalstorm", "M.exe", epic = EpicOptions(eos = true, offline = true))
val back = StoreGameSidecar.parse(set.toJson().toString())!!
assertEquals(EpicOptions(eos = true, offline = true), back.epic)
assertFalse(back.epic.wantsCode)
// A sidecar from before the choices existed reads as the defaults.
assertEquals(EpicOptions(), StoreGameSidecar.parse("""{"store":"epic","id":"m","title":"M","exe":"M.exe"}""")!!.epic)
// An earlier build's overlay field is read past.
assertEquals(EpicOptions(), StoreGameSidecar.parse("""{"store":"epic","id":"m","title":"M","exe":"M.exe","epic":{"v":2,"eos":true,"offline":false,"overlay":true}}""")!!.epic)
}
@Test fun aSwitchOnTheEpicCardChangesTheSidecarOnDisk() {
val folder = java.io.File(org.robolectric.RuntimeEnvironment.getApplication().filesDir, "Games/Stores/Epic/Metalstorm").apply { mkdirs() }
StoreGameSidecar(Store.EPIC, "m", "Metalstorm", "Metalstorm.exe", launcher = ".droiddeck-launch.bat").write(folder)
val written = StoreGameSidecar.updateEpic(folder) { it.copy(offline = true) }!!
assertTrue(written.epic.offline)
// What the Steam-launch helper reads: the file itself.
val onDisk = org.json.JSONObject(java.io.File(folder, StoreGameSidecar.FILE_NAME).readText())
assertTrue(onDisk.getJSONObject("epic").getBoolean("offline"))
assertTrue(onDisk.getJSONObject("epic").getBoolean("eos"))
assertFalse(onDisk.getJSONObject("epic").has("overlay"))
// Everything else in it stays.
assertEquals(".droiddeck-launch.bat", StoreGameSidecar.read(folder)!!.launcher)
assertEquals(null, StoreGameSidecar.updateEpic(java.io.File(folder, "missing")) { it })
}
@Test fun anInstallUnderWayHasNoExeYetAndIsNotInstalled() {
val started = StoreGameSidecar(Store.EPIC, "Metalstorm", "Metalstorm", exe = "", state = StoreGameSidecar.STATE_INSTALLING)
val back = StoreGameSidecar.parse(started.toJson().toString())!!
assertFalse(back.isInstalled)
assertEquals("", back.exe)
// A finished one must still name its exe.
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":""}"""))
assertTrue(StoreGameSidecar.parse(back.copy(exe = "Metalstorm.exe", state = StoreGameSidecar.STATE_INSTALLED).toJson().toString())!!.isInstalled)
}
@Test fun refusesWhatIsNotASidecar() {
assertNull(StoreGameSidecar.parse("not json"))
assertNull(StoreGameSidecar.parse("""{"store":"steam","id":"1","title":"T","exe":"a.exe"}"""))
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"","title":"T","exe":"a.exe"}"""))
// An exe outside the folder is not trusted: a sidecar must not point the shortcut anywhere.
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"../other/a.exe"}"""))
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"/abs/a.exe"}"""))
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"C:\\a.exe"}"""))
}
@Test fun folderNamesAreSafeAndStable() {
assertEquals("Heroes of Might and Magic 3 Complete", StoreInstallRoot.folderName("Heroes of Might and Magic 3: Complete", "1"))
assertEquals("What Remains of Edith Finch", StoreInstallRoot.folderName("What Remains of Edith Finch...", "1"))
assertEquals("1207658924", StoreInstallRoot.folderName("日本語のみ", "1207658924"))
assertTrue(StoreInstallRoot.folderName("x".repeat(200), "1").length <= 60)
}
@Test fun launcherStartsTheExeFromItsFolderWithArgsAndEnv() {
val text = StoreLaunch.launcherText(sample.copy(exe = "Binaries/Win64/Celeste.exe"))
assertTrue(text.contains("cd /d \"%~dp0Binaries\\Win64\"\r\n"))
assertTrue(text.contains("set \"FOO=bar\"\r\n"))
assertTrue(text.contains("\r\n\"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\"\r\n"))
// Epic reads the one-shot exchange code the app leaves beside the launcher, then deletes it.
assertTrue(text.contains("set /p DD_X=<\"%~dp0.droiddeck-epic-code\""))
// The code goes on the command line only: the variable is cleared on the very line that
// starts the game (cmd has already expanded it there), so the game inherits none of it.
assertTrue(text.contains("set \"DD_X=\" & \"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\" -AUTH_LOGIN=unused -AUTH_PASSWORD=%DD_X% -AUTH_TYPE=exchangecode\r\n"))
assertFalse(text.contains("AUTH="))
assertFalse(text.contains("DD_AUTH"))
}
@Test fun gogLauncherHasNoEpicBlockAndIsOnlyWrittenWhenNeeded() {
val plain = StoreGameSidecar(Store.GOG, "1", "T", "game.exe")
val text = StoreLaunch.launcherText(plain.copy(args = listOf("-windowed")))
assertFalse(text.contains("exchangecode"))
assertTrue(text.contains("\"%~dp0game.exe\" -windowed\r\n"))
assertFalse(text.contains("DD_X"))
assertEquals("\"two words\"", StoreLaunch.quoteArg("two words"))
assertEquals("-x=\"a b\"", StoreLaunch.quoteArg("-x=\"a b\""))
}
}
@@ -0,0 +1,62 @@
package com.droiddeck.launcher.stores
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** Where a store game goes: internal storage unless the user picks a card, and back to its own folder on a rerun. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class StoreInstallRootTest {
private val app get() = RuntimeEnvironment.getApplication()
@Test fun theDefaultRootIsInternalWhateverTheSteamLibrarySettingSays() {
val card = File(app.filesDir, "fake-card/steam").apply { mkdirs() }
SessionPrefs.setGameStorage(app, card.path, "Card")
assertEquals(File(LinuxRuntime.rootDir(app), "root/Games/Stores").absolutePath, StoreInstallRoot.installRoot(app).absolutePath)
// The library's Games folder is still scanned, for installs an earlier build put there.
assertTrue(StoreInstallRoot.roots(app).any { it.absolutePath == File(card, "Games").absolutePath })
assertFalse(StoreInstallRoot.targets(app).first().removable)
}
@Test fun anExistingInstallWinsOverAFreshFolderUnderTheChosenRoot() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val existing = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "Old Name").apply { mkdirs() }
StoreGameSidecar(Store.GOG, "42", "New Name", "game.exe").write(existing)
val other = File(app.filesDir, "elsewhere/Games")
assertEquals(existing.absolutePath, StoreInstallRoot.folderFor(app, Store.GOG, "42", "New Name", other).absolutePath)
assertEquals(File(StoreInstallRoot.storeDir(other, Store.GOG), "Fresh").absolutePath, StoreInstallRoot.folderFor(app, Store.GOG, "7", "Fresh", other).absolutePath)
}
@Test fun aFolderLeftWithoutASidecarIsAnUnfinishedInstallAndIsResumedInPlace() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val epic = StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.EPIC)
val half = File(epic, StoreInstallRoot.folderName("Metalstorm", "abc")).apply { mkdirs() }
File(half, ".chunks").mkdirs()
File(half, "Metalstorm.exe").writeText("MZ")
assertFalse(StoreInstallRoot.isFinished(half))
assertTrue(StoreInstallRoot.unfinished(app).any { it.store == Store.EPIC && it.id == null && it.folder.absolutePath == half.absolutePath })
// Install again, even with another root picked: the same folder, no duplicate.
assertEquals(half.absolutePath, StoreInstallRoot.folderFor(app, Store.EPIC, "abc", "Metalstorm", File(app.filesDir, "card/Games")).absolutePath)
// Begun and finished: the folder becomes a game.
StoreInstalls.begin(half, Store.EPIC, "abc", "Metalstorm", null, null)
assertTrue(StoreInstallRoot.unfinished(app).any { it.id == "abc" })
StoreGameSidecar(Store.EPIC, "abc", "Metalstorm", "Metalstorm.exe").write(half)
assertTrue(StoreInstallRoot.isFinished(half))
assertTrue(StoreInstallRoot.unfinished(app).none { it.folder.absolutePath == half.absolutePath })
}
@Test fun theScratchCacheIsPrivateAndNamedSafely() {
val dir = StoreInstallRoot.scratchDir(app, Store.EPIC, "a/b:c")
assertTrue(dir.absolutePath.startsWith(app.cacheDir.absolutePath))
assertEquals("a_b_c", dir.name)
}
}
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.stores
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Test
/** Store lines reach the Downloads log and logcat; nothing in them may carry a token. */
class StoreLogTest {
@Test fun gogSecureLinkKeepsOnlyTheHost() {
val line = "gog: window 32 in_flight 3 https://gog-cdn-fastly.gog.com/token=nva=1791500000~dirs=/content-system/v2/store/1207658924~token=0a1b2c3d4e5f/content-system/v2/store/1207658924/ab/cd/abcdef 12.1 MB/s"
val out = StoreLog.redactLine(line)
assertEquals("gog: window 32 in_flight 3 https://gog-cdn-fastly.gog.com/… 12.1 MB/s", out)
assertFalse(out.contains("0a1b2c3d4e5f"))
}
@Test fun epicAkamaiUrlLosesItsQueryAndPath() {
val line = "epic: CDN https://epicgames-download1.akamaized.net/Builds/Org/o-abc/xyz/default/ChunksV4/12/ABCD.chunk?__token__=exp=1791500000~acl=/*~hmac=deadbeef&f_token=xyz done"
val out = StoreLog.redactLine(line)
assertEquals("epic: CDN https://epicgames-download1.akamaized.net/Builds/… done", out)
}
@Test fun tokensOutsideUrlsAndHeadersAreBlanked() {
val out = StoreLog.redactLine("refresh access_token=abc.def refresh_token: 'xyz' code=AUTH123 hdnts=exp~hmac __token__=q")
assertEquals("refresh access_token=… refresh_token: '…' code=… hdnts=… __token__=…", out)
assertEquals("Authorization: …", StoreLog.redactLine("Authorization: Bearer eyJhbGciOi"))
assertEquals("""{"access_token":"…","expires_in":7200}""", StoreLog.redactLine("""{"access_token":"eyJ.abc","expires_in":7200}"""))
// Ordinary numbers stay: "HTTP code 403" has no separator to read as a secret.
assertEquals("HTTP code 403 from https://api.gog.com/products/…", StoreLog.redactLine("HTTP code 403 from https://user:pw@api.gog.com/products/1?expand=x"))
}
}
@@ -0,0 +1,31 @@
package com.droiddeck.launcher.stores.download
import com.droiddeck.launcher.stores.Store
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/** The Downloads row reads the active stage's own progress, and which stages are behind it. */
class DownloadEntryTest {
private val base = DownloadEntry(Store.EPIC, "doomblade", "DOOMBLADE", state = DownloadState.RUNNING)
@Test fun downloadRunsOnBytesAndInstallOnItsOwnCount() {
val dl = base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 50, bytesTotal = 200)
assertEquals(0.25f, dl.stageFraction, 0.001f)
// Past Download the bytes no longer drive the bar; the stage's own count does.
val inst = dl.copy(stage = DownloadStage.INSTALL, stageDone = 30, stageTotal = 40, stageItems = 3, stageItemsTotal = 4)
assertEquals(0.75f, inst.stageFraction, 0.001f)
assertEquals(75, inst.percent)
// Nothing counted yet: unknown, not empty and not full.
assertEquals(-1f, base.copy(stage = DownloadStage.INSTALL).stageFraction, 0f)
}
@Test fun passedStagesComeFromTheBitsNotTheOrder() {
// Epic checks files before it fetches: Verify is behind Download there.
val e = base.copy(stage = DownloadStage.DOWNLOAD, stagesPassed = (1 shl DownloadStage.MANIFEST.ordinal) or (1 shl DownloadStage.VERIFY.ordinal))
assertTrue(e.passed(DownloadStage.VERIFY))
assertFalse(e.passed(DownloadStage.INSTALL))
assertTrue(e.copy(state = DownloadState.INSTALLED).passed(DownloadStage.INSTALL))
}
}
@@ -0,0 +1,21 @@
package com.droiddeck.launcher.stores.download
import com.droiddeck.launcher.stores.Store
import org.junit.Assert.assertEquals
import org.junit.Test
/** The notification's line: what the Downloads row says, on one line. */
class DownloadNotificationTextTest {
private val base = DownloadEntry(Store.EPIC, "m", "Metalstorm", state = DownloadState.RUNNING)
@Test fun downloadingShowsPercentSizesSpeedAndTime() {
val d = base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 1_288_490_189, bytesTotal = 2_684_354_560, speedBps = 12_897_484, etaSeconds = 185)
assertEquals("Metalstorm · 48% · 1.2 GB/2.5 GB · 12.3 MB/s · 3 min", DownloadNotificationText.line(d, "Downloading", "Paused", "Queued"))
}
@Test fun installShowsTheStageNotTheSpeed() {
val d = base.copy(stage = DownloadStage.INSTALL, stageDone = 42, stageTotal = 100, speedBps = 50_000_000)
assertEquals("Metalstorm · Installing 42%", DownloadNotificationText.line(d, "Installing", "Paused", "Queued"))
assertEquals("Metalstorm · Paused", DownloadNotificationText.line(d.copy(state = DownloadState.PAUSED), "Installing", "Paused", "Queued"))
}
}
@@ -0,0 +1,31 @@
package com.droiddeck.launcher.stores.gog
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** Every CDN GOG's secure link offers is used, not only the first. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GogCdnTest {
private val answer = """{"urls":[
{"endpoint_name":"fastly","url_format":"https:\/\/gog-cdn-fastly.gog.com\/token=nva={expires_at}~token={token}/{path}","parameters":{"expires_at":1,"token":"t"}},
{"endpoint_name":"akamai","url_format":"{base_url}/{path}","parameters":{"base_url":"https://gog-cdn-akamai.gog.com/s"}},
{"endpoint_name":"lumen","url_format":"https://cdn.gog.com/{path}","parameters":{}}
]}"""
@Test fun allHostsAreParsedInOrderAndTakenInTurn() {
val all = GogDownloadManager.parseCdnUrls(answer)
assertEquals(3, all.size)
assertEquals("https://gog-cdn-fastly.gog.com/token=nva=1~token=t", all[0])
assertEquals("https://gog-cdn-akamai.gog.com/s", all[1])
assertEquals("https://cdn.gog.com", all[2])
val set = all.joinToString("\n")
assertEquals(all[0], GogDownloadManager.firstCdn(set))
val picks = (0 until 6).map { GogDownloadManager.pickCdn(set) }.toSet()
assertEquals(all.toSet(), picks)
assertEquals(0, GogDownloadManager.parseCdnUrls("not json").size)
}
}
@@ -0,0 +1,18 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.stores.Store
import org.junit.Assert.assertEquals
import org.junit.Test
/** Amazon has no catalog of its own: Installed and Library only, and Store falls back to Library. */
class StoreTabsTest {
@Test fun storeAndLibraryAmazonLibraryOnly() {
assertEquals(listOf("store", "library"), tabsFor(Store.GOG))
assertEquals(listOf("library"), tabsFor(Store.AMAZON))
assertEquals("library", tabFor(Store.AMAZON, "store"))
// An old saved Installed or All tab opens Library.
assertEquals("library", tabFor(Store.GOG, "all"))
assertEquals("library", tabFor(Store.EPIC, "installed"))
assertEquals("store", tabFor(Store.GOG, "store"))
}
}