diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index a6478cd109..80216a939a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -60,6 +60,8 @@ object SessionFiles { "usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks", "usr/local/bin/droiddeck-steam-shim" to "usr/local/bin/droiddeck-steam-shim", "usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts", + // Asks the app for an Epic game's sign-in code at launch, from the compat tool (StoreLaunchRequests). + "usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch", "usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games", "usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults", // Flatpak: the bwrap stand-in, the store's helper and setup, and the front end's launcher. diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 42e0083877..c0be147ce6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -325,6 +325,8 @@ class SessionService : Service() { killStragglers() SessionFiles.stage(this, root) com.droiddeck.launcher.agent.AgentGuest.reset(this) + // The compat tool asks for an Epic game's sign-in code at every launch, the client's Play button included. + com.droiddeck.launcher.stores.StoreLaunchRequests.start(this) val sessionDir = openSessionFolder() val sessionLog = File(sessionDir, "session.log") @@ -1414,6 +1416,7 @@ class SessionService : Service() { pipTask = false SessionState.guestPid = -1 com.droiddeck.launcher.agent.AgentGuest.stop() + com.droiddeck.launcher.stores.StoreLaunchRequests.stop() runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) } .onFailure { Log.w(TAG, "clearing the agent's session environment", it) } releaseLocks() diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt index 9167a91ba4..0cf7bd6180 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt @@ -74,22 +74,46 @@ object StoreLaunch { if (store != Store.EPIC) { onReady(); return } val app = context.applicationContext Thread({ - try { - val game = StoreInstallRoot.gameFolders(app).firstOrNull { folder -> StoreGameSidecar.read(folder)?.let { it.store == store && it.id == id } == true } - if (game != null) { - val code = StoresState.backend(Store.EPIC)?.let { (it as? EpicLaunchSupport)?.exchangeCode(app) } - val file = File(game, EPIC_CODE) - if (code != null) { file.writeText(code); Log.i(TAG, "epic: exchange code ready for $id") } - else { file.delete(); Log.w(TAG, "epic: no exchange code; launching offline") } - } - } catch (e: Exception) { - Log.w(TAG, "epic prepare: ${e.message}") - } + epicCode(app, id) StoresState.post(onReady) }, "stores-launch-prep").start() } - /** The same, for a game the Games tab launches: a store's game by its [Library.SteamGame.source]. */ + /** What [epicCode] did, for the guest's request and the log: whether a code was written, and why not. */ + class CodeResult(val written: Boolean, val reason: String) + + /** + * Mints an Epic exchange code for the installed game [id] and writes it as [EPIC_CODE] into the + * very folder its sidecar and launcher are in, where the launcher .bat reads and deletes it. + * Blocking (network). Logs `epic launch id= code=yes|no reason=...` - never the code. Every + * launch path comes here: the Games tab and Stores before they launch, and the compat tool for + * any launch, the Steam client's own Play button included ([StoreLaunchRequests]). + */ + fun epicCode(context: Context, id: String): CodeResult { + val app = context.applicationContext + val result = try { + val folder = StoreInstallRoot.gameFolders(app).firstOrNull { f -> StoreGameSidecar.read(f)?.let { it.store == Store.EPIC && it.id == id } == true } + if (folder == null) CodeResult(false, "not-installed") + else { + val file = File(folder, EPIC_CODE) + file.delete() + val support = StoresState.backend(Store.EPIC) as? EpicLaunchSupport + val code = support?.exchangeCode(app) + when { + support == null -> CodeResult(false, "no-backend") + code != null -> { file.writeText(code); CodeResult(true, "ok") } + StoreAccounts.signedInAs(app, Store.EPIC) == null -> CodeResult(false, "signed-out") + support.signInExpired(app) -> { StoresState.markSignInExpired(Store.EPIC); CodeResult(false, "sign-in-expired") } + else -> CodeResult(false, "exchange-failed") + } + } + } catch (e: Exception) { + CodeResult(false, "error-" + e.javaClass.simpleName) + } + Log.i(TAG, "epic launch id=$id code=${if (result.written) "yes" else "no"} reason=${result.reason}") + return result + } + fun prepare(context: Context, game: Library.SteamGame, onReady: () -> Unit) { val store = Store.byId(game.source) val id = game.storeId @@ -101,4 +125,6 @@ object StoreLaunch { /** What the Epic backend adds for launches: a short-lived exchange code for the signed-in account. */ interface EpicLaunchSupport { fun exchangeCode(context: Context): String? + /** True when the stored sign-in can no longer be refreshed: the user has to sign in again. */ + fun signInExpired(context: Context): Boolean } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt new file mode 100644 index 0000000000..6d2c881bc0 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt @@ -0,0 +1,74 @@ +package com.droiddeck.launcher.stores + +import android.content.Context +import android.os.FileObserver +import android.util.Log +import com.droiddeck.launcher.runtime.LinuxRuntime +import java.io.File +import org.json.JSONObject + +/** + * The app's half of droiddeck-store-launch: the compat tool asks, before Proton starts a store + * game, for what the store needs at launch, through files under the session root's `stores/` + * (`req/.json` in, `resp/.json` out, both written tmp + rename). Today that is an Epic + * game's exchange code, which [StoreLaunch.epicCode] writes into the game's own folder; the answer + * says only whether it did and why not. Watched while a session runs. + */ +object StoreLaunchRequests { + private const val TAG = "StoreLaunchRequests" + private val lock = Any() + private var observer: FileObserver? = null + + fun dir(context: Context) = File(LinuxRuntime.sessionRoot(context), "stores") + + /** Before each session: nothing of the last one's requests; then watch for new ones. */ + fun start(context: Context) { + val app = context.applicationContext + synchronized(lock) { + observer?.stopWatching() + val root = dir(app) + root.deleteRecursively() + val req = File(root, "req").apply { mkdirs() } + File(root, "resp").mkdirs() + @Suppress("DEPRECATION") + observer = object : FileObserver(req.path, MOVED_TO or CLOSE_WRITE) { + override fun onEvent(event: Int, path: String?) { + if (path == null || !path.endsWith(".json")) return + val file = File(req, path) + Thread({ answer(app, file) }, "store-launch-request").start() + } + }.also { it.startWatching() } + } + } + + fun stop() { + synchronized(lock) { + observer?.stopWatching() + observer = null + } + } + + private fun answer(app: Context, file: File) { + val request = try { + JSONObject(file.readText()).also { file.delete() } + } catch (e: Exception) { + return // withdrawn already, or not complete yet (the rename brings it again) + } + val reply = when (request.optString("op")) { + "epic-code" -> { + val id = request.optString("id") + if (id.isEmpty()) JSONObject().put("ok", false).put("reason", "no-id") + else StoreLaunch.epicCode(app, id).let { JSONObject().put("ok", true).put("code", it.written).put("reason", it.reason) } + } + else -> JSONObject().put("ok", false).put("reason", "unknown-op") + } + try { + val resp = File(dir(app), "resp").apply { mkdirs() } + val tmp = File(resp, file.name + ".tmp") + tmp.writeText(reply.toString()) + tmp.renameTo(File(resp, file.name)) + } catch (e: Exception) { + Log.w(TAG, "could not answer ${file.name}: ${e.message}") + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index cf097ef4a0..4d15d2f149 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -118,6 +118,11 @@ object StoresState { fun isSignedIn(store: Store): Boolean = accounts.containsKey(store) + /** Stores whose sign-in has run out (a launch could not get a code): their chip dims until the user signs in again. */ + val expired = mutableStateMapOf() + + fun markSignInExpired(store: Store) = post { expired[store] = true } + /** Installs that stopped before they finished; their Install button reads "Resume install". */ var unfinished by mutableStateOf>(emptyList()) internal set @@ -149,6 +154,7 @@ object StoresState { } fun signIn(context: Context, store: Store) { + expired.remove(store) backends[store]?.signIn(context) ?: logLine("${store.label}: this build has no sign-in for it yet") } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicAuthClient.java b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicAuthClient.java index fef64d7dfd..959d4302b9 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicAuthClient.java +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicAuthClient.java @@ -95,7 +95,8 @@ public final class EpicAuthClient { public static String getExchangeCode(String accessToken) { try { String resp = getRequest(EXCHANGE_URL, accessToken); - if (resp == null) return null; + // getRequest has logged the HTTP status; the code itself is never logged. + if (resp == null) { Log.i(TAG, "exchange code: no answer"); return null; } return new JSONObject(resp).optString("code", null); } catch (Exception e) { Log.e(TAG, "exchange code failed: " + e.getClass().getSimpleName()); diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt index 622268476a..3b953f4321 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt @@ -97,6 +97,9 @@ object EpicBackend : StoreBackend, EpicLaunchSupport { return EpicAuthClient.getExchangeCode(token) } + /** The access token is past its time and the refresh just failed: only a new sign-in helps. */ + override fun signInExpired(context: Context): Boolean = EpicCredentialStore.expired(context) + private class InstallJob(val app: Context, val item: CatalogItem, val namespace: String, val catalogItemId: String, val folder: File) : DownloadQueue.DownloadJob { private val cancelled = AtomicBoolean(false) // On a card the in-flight chunks go to the app's cache instead: the card's write rate paces diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicCredentialStore.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicCredentialStore.kt index 3fea58fd41..abf545ae13 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicCredentialStore.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicCredentialStore.kt @@ -36,6 +36,12 @@ object EpicCredentialStore { /** A valid access token, refreshed when within five minutes of expiry; null when signed out or the refresh failed. */ @JvmStatic + /** The stored access token is past its expiry (a refresh, if one was tried, did not replace it). */ + fun expired(context: Context): Boolean { + val creds = load(context) ?: return false + return creds.expiresAt in 1 until System.currentTimeMillis() + } + fun getValidAccessToken(context: Context): String? { val creds = load(context) ?: return null if (creds.expiresAt - System.currentTimeMillis() < 5L * 60L * 1000L && creds.refreshToken != null) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index e4ef136036..dc050c9abc 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -163,7 +163,8 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier when { chip == DOWNLOADS -> StoresDownloadsPane(s, a) store == null -> {} - !StoresState.isSignedIn(store) -> Rise(1) { SignInCard(store) } + // Signed out, or a sign-in that ran out (a launch could not get its code): sign in again. + !StoresState.isSignedIn(store) || StoresState.expired[store] == true -> Rise(1) { SignInCard(store) } // One focus group, so the pad walks the page's own controls - back, the hero's // actions, the cards - and reaches the rail only with Left from them. openGame != null -> Column(Modifier.fillMaxWidth().focusGroup()) { StoreGameDetail(store, openGame!!, s, a, onBack = { closeGame() }) } @@ -191,9 +192,9 @@ private fun StoreChips(selected: String, active: Int, onPick: (String) -> Unit, label = store.shortLabel, on = selected == store.id, key = store.id, modifier = Modifier.weight(1f), lead = { val c = sourceColours(store.id) - Box(Modifier.size(12.dp).clip(CircleShape).background(c.dot).alpha(if (StoresState.isSignedIn(store)) 1f else 0.35f)) + Box(Modifier.size(12.dp).clip(CircleShape).background(c.dot).alpha(if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) 1f else 0.35f)) }, - description = store.label + if (StoresState.isSignedIn(store)) "" else " " + stringResource(R.string.stores_chip_signed_out), + description = store.label + if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) "" else " " + stringResource(R.string.stores_chip_signed_out), ) { onPick(store.id) } } StoreChip( diff --git a/docs/progress-log.md b/docs/progress-log.md index 29a4ad2581..9f78678bde 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -144,6 +144,18 @@ without it and Setup says "Stores engine not built"). (`token`, `__token__`, `f_token`, `hdnts`, access/refresh/id tokens, `code=`) and Authorization / Cookie headers are blanked outside URLs too. `StoreLogTest` covers a GOG secure link and an Epic Akamai URL. The engine's own logcat lines (tag `EpicNative` etc.) are written on the native side. +- **Epic sign-in from Steam's own Play button (device, Metalstorm "Guest Account"):** the game was + started from the Steam client, so the app never minted its exchange code - the code was only + written when a launch began in the app. Now the compat tool (`droiddeck-proton` and + `droiddeck-proton-wrap`, `steam-compatibility`) runs `droiddeck-store-launch` on every real launch: + it recognises the store launcher among Steam's arguments, and for an Epic game asks the app + through `/stores/req|resp` and waits up to 5 s; the app (`StoreLaunchRequests` → + `StoreLaunch.epicCode`) refreshes the token, mints the code and writes it into the game's own + folder - the code never crosses the channel or the log. No answer: the game starts with its + offline identity. A code file older than five minutes is dropped first. Every attempt logs + `epic launch id= code=yes|no reason=`; + a sign-in that ran out dims the Epic chip and shows the sign-in card. The Games tab and Stores + still prepare a code before they launch; the compat tool's request is the one every path shares. - **Amazon has Installed and Library only:** with no public catalog its Store tab repeated the library (Trending = Your library) and All equalled Library. The open-on Store choice falls back to Library for Amazon. Amazon's library API carries no install size, so a size shows only once a diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch new file mode 100755 index 0000000000..527b77ac92 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch @@ -0,0 +1,123 @@ +#!/usr/bin/python3 +"""Before Proton starts a store game, asks the app for what that store needs at launch. + +Run by droiddeck-proton / droiddeck-proton-wrap (steam-compatibility) for every real game launch, +whoever started it: the Games tab, a pinned shortcut, or the Steam client's own Play button. It +looks for the store launcher DroidDeck wrote (.droiddeck-launch.bat) among the arguments; beside it +.droiddeck-store.json says which store and game it is. + +For an Epic game the game needs a fresh exchange code to sign in, which only the app can mint. The +request goes through files under $BL_LAUNCH_DIR/stores (the session root, the same path on both +sides): + + req/.json {"op": "epic-code", "store": "epic", "id": ""} (tmp + rename) + resp/.json {"ok": true, "code": true|false, "reason": "..."} + +The app writes .droiddeck-epic-code into the game's folder itself - the code never passes through +here - and the launcher .bat reads and deletes it. No answer within TIMEOUT seconds: the game starts +with its offline identity. A code file older than STALE_SECONDS is removed first, so a code left by +an earlier launch is never used. + + droiddeck-store-launch +""" + +import json +import os +import sys +import time +from pathlib import Path + +LAUNCHER = ".droiddeck-launch.bat" +SIDECAR = ".droiddeck-store.json" +EPIC_CODE = ".droiddeck-epic-code" +TIMEOUT = 5.0 +STALE_SECONDS = 300 + + +def log(line): + print("droiddeck-store-launch: " + line, file=sys.stderr, flush=True) + + +def find_store_game(argv): + """The (folder, sidecar) of the store launcher among [argv], or None when this is not one.""" + for raw in argv: + arg = raw.strip().strip('"').strip("'") + if not arg.lower().endswith(LAUNCHER): + continue + folder = Path(arg.replace("\\", "/")).parent + try: + sidecar = json.loads((folder / SIDECAR).read_text()) + except (OSError, ValueError): + continue + if not isinstance(sidecar, dict) or not sidecar.get("store") or not sidecar.get("id"): + continue + return folder, sidecar + return None + + +def drop_stale(folder, now=None): + """Removes a code file older than STALE_SECONDS; True when one was removed.""" + code = folder / EPIC_CODE + try: + if (now if now is not None else time.time()) - code.stat().st_mtime > STALE_SECONDS: + code.unlink() + return True + except OSError: + pass + return False + + +def ask(channel, request, timeout=TIMEOUT): + """Writes [request] under channel/req and waits for channel/resp; the answer, or None on timeout.""" + req_dir, resp_dir = channel / "req", channel / "resp" + req_dir.mkdir(parents=True, exist_ok=True) + resp_dir.mkdir(parents=True, exist_ok=True) + rid = "%d-%d" % (os.getpid(), int(time.time() * 1000)) + tmp = req_dir / (rid + ".json.tmp") + tmp.write_text(json.dumps(request)) + os.rename(tmp, req_dir / (rid + ".json")) + answer = resp_dir / (rid + ".json") + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + value = json.loads(answer.read_text()) + answer.unlink() + return value + except (OSError, ValueError): + time.sleep(0.05) + # Not answered: the request is withdrawn so a late app does not mint a code nobody reads. + try: + (req_dir / (rid + ".json")).unlink() + except OSError: + pass + return None + + +def main(argv): + found = find_store_game(argv) + if found is None: + return 0 + folder, sidecar = found + store, game = str(sidecar.get("store")), str(sidecar.get("id")) + if store != "epic": + return 0 + drop_stale(folder) + launch_dir = os.environ.get("BL_LAUNCH_DIR", "") + if not launch_dir: + log("epic launch id=%s code=no reason=no-channel" % game) + return 0 + answer = ask(Path(launch_dir) / "stores", {"op": "epic-code", "store": store, "id": game}) + if answer is None: + log("epic launch id=%s code=no reason=timeout" % game) + else: + got = bool(answer.get("code")) + log("epic launch id=%s code=%s reason=%s" % (game, "yes" if got else "no", answer.get("reason", ""))) + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main(sys.argv[1:])) + except Exception as e: # never in the way of the launch + log("skipped: %s" % type(e).__name__) + sys.exit(0) diff --git a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility index 351e32b0c2..96bcce6495 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -96,6 +96,18 @@ TOOL_MANIFEST_VDF = """"manifest" # each package in use. A file that no longer matches - whatever changed it - is put back before # Proton starts. Only for the Proton build the choice was made for: after a Steam update the build # differs and the Proton's own new files are left alone until the user chooses again. +# A store game (GOG, Epic, Amazon) is started through the launcher .bat DroidDeck wrote beside it. +# An Epic game needs a fresh sign-in code, which only the app can mint: droiddeck-store-launch asks +# for it and the app writes it into the game's folder, so a launch from the client's own Play +# button signs in just as one from the app does. A real launch only; never in the way of it. +BL_STORE_SETUP = """ +bl_store_launch() { + [ "${verb:-}" = waitforexitandrun ] || return 0 + [ -x /usr/local/bin/droiddeck-store-launch ] || return 0 + /usr/local/bin/droiddeck-store-launch "$@" || true +} +""" + BL_COMPONENTS_SETUP = """ bl_components() { base=$1 @@ -332,6 +344,7 @@ if [ -n "$depot" ]; then bl_game_cpus bl_idtech3 "$@" bl_libpath + bl_store_launch "$@" exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" fi echo "droiddeck-proton: no ARM64 Proton depot yet - the client downloads one as this tool's dependency; retry the launch once it has" >&2 @@ -346,7 +359,7 @@ def launcher_sh(sources=SOURCES): # something else. return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace( "verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP - + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1) + + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1) LAUNCHER_SH = launcher_sh() @@ -390,6 +403,7 @@ bl_directaudio "$here" bl_game_cpus bl_idtech3 "$@" bl_libpath +bl_store_launch "$@" # Proton takes its base directory from dirname(sys.argv[0]) without resolving it, so it has to be # started from its own tree. exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env "$here/%s" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" @@ -619,7 +633,7 @@ def adopt_extras(tools): body = (EXTRA_WRAPPER_SH % entry_point).replace( 'here=$(dirname "$0")', 'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP - + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1) + + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1) write_changed(wrapper, body, 0o755) write_changed(manifest, EXTRA_MANIFEST_VDF) write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, display_name(entry))) diff --git a/tools/tests/test_store_launch.py b/tools/tests/test_store_launch.py new file mode 100644 index 0000000000..cad02ac755 --- /dev/null +++ b/tools/tests/test_store_launch.py @@ -0,0 +1,117 @@ +"""droiddeck-store-launch: a launch from anywhere - the Steam client's own Play button included - +asks the app for an Epic game's sign-in code before Proton starts. These pin how it recognises a +store game, how it asks, and that both Proton launchers call it.""" +import importlib.machinery +import importlib.util +import json +import os +from pathlib import Path +import tempfile +import threading +import time +import unittest + +BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin' + + +def load(name): + loader = importlib.machinery.SourceFileLoader(name.replace('-', '_'), str(BIN / name)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +store = load('droiddeck-store-launch') +compat = load('steam-compatibility') + + +def game(root, store_id='epic', ident='8b6a0e14'): + folder = Path(root) / 'Games/Stores/Epic/Metalstorm' + folder.mkdir(parents=True) + (folder / '.droiddeck-store.json').write_text(json.dumps({'store': store_id, 'id': ident, 'title': 'Metalstorm', 'exe': 'Metalstorm.exe'})) + (folder / '.droiddeck-launch.bat').write_text('@echo off\r\n') + return folder + + +class Detection(unittest.TestCase): + def test_the_launcher_among_steams_arguments_names_the_game(self): + with tempfile.TemporaryDirectory() as root: + folder = game(root) + found = store.find_store_game(['/usr/bin/steam-runtime', '"%s/.droiddeck-launch.bat"' % folder, '-flag']) + self.assertIsNotNone(found) + self.assertEqual(folder, found[0]) + self.assertEqual('epic', found[1]['store']) + self.assertEqual('8b6a0e14', found[1]['id']) + + def test_anything_else_is_left_alone(self): + with tempfile.TemporaryDirectory() as root: + folder = game(root) + self.assertIsNone(store.find_store_game([str(folder / 'Metalstorm.exe')])) + (folder / '.droiddeck-store.json').unlink() + self.assertIsNone(store.find_store_game([str(folder / '.droiddeck-launch.bat')])) + + def test_only_epic_asks(self): + with tempfile.TemporaryDirectory() as root: + folder = game(root, store_id='gog') + os.environ['BL_LAUNCH_DIR'] = str(Path(root) / 'session') + try: + self.assertEqual(0, store.main([str(folder / '.droiddeck-launch.bat')])) + finally: + del os.environ['BL_LAUNCH_DIR'] + self.assertFalse((Path(root) / 'session/stores').exists()) + + +class Asking(unittest.TestCase): + def test_a_request_is_answered_through_the_resp_folder(self): + with tempfile.TemporaryDirectory() as root: + channel = Path(root) / 'stores' + + def app(): + req = channel / 'req' + for _ in range(100): + names = [p for p in req.glob('*.json')] if req.exists() else [] + if names: + request = json.loads(names[0].read_text()) + self.assertEqual({'op': 'epic-code', 'store': 'epic', 'id': 'x'}, request) + names[0].unlink() + tmp = channel / 'resp' / (names[0].name + '.tmp') + tmp.write_text(json.dumps({'ok': True, 'code': True, 'reason': 'ok'})) + os.rename(tmp, channel / 'resp' / names[0].name) + return + time.sleep(0.02) + + t = threading.Thread(target=app) + t.start() + answer = store.ask(channel, {'op': 'epic-code', 'store': 'epic', 'id': 'x'}, timeout=3) + t.join() + self.assertEqual({'ok': True, 'code': True, 'reason': 'ok'}, answer) + + def test_no_answer_withdraws_the_request(self): + with tempfile.TemporaryDirectory() as root: + channel = Path(root) / 'stores' + self.assertIsNone(store.ask(channel, {'op': 'epic-code'}, timeout=0.2)) + self.assertEqual([], list((channel / 'req').iterdir())) + + def test_a_stale_code_is_dropped_before_asking(self): + with tempfile.TemporaryDirectory() as root: + folder = game(root) + code = folder / '.droiddeck-epic-code' + code.write_text('old') + self.assertFalse(store.drop_stale(folder, now=code.stat().st_mtime + 60)) + self.assertTrue(store.drop_stale(folder, now=code.stat().st_mtime + store.STALE_SECONDS + 1)) + self.assertFalse(code.exists()) + + +class Launchers(unittest.TestCase): + def test_both_proton_launchers_ask_before_proton_starts(self): + sh = compat.LAUNCHER_SH + self.assertIn('bl_store_launch() {', sh) + self.assertLess(sh.index('bl_store_launch "$@"'), sh.index('droiddeck-game-env "$depot/proton"')) + self.assertIn('bl_store_launch "$@"', compat.EXTRA_WRAPPER_SH) + self.assertIn('bl_store_launch() {', compat.BL_STORE_SETUP) + self.assertIn('waitforexitandrun', compat.BL_STORE_SETUP) + + +if __name__ == '__main__': + unittest.main()