Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7b36f5a4f | ||
|
|
ffb2a3d6e6 | ||
|
|
aff81a13e3 | ||
|
|
570d40f825 | ||
|
|
3dbcefc14c | ||
|
|
9cbad0b1ac | ||
|
|
f524ffc3d6 | ||
|
|
1fe92c978a | ||
|
|
1f016211f2 | ||
|
|
49c5ff188b | ||
|
|
46f99b9e08 | ||
|
|
dcb1a3001b | ||
|
|
dbfcd764f3 | ||
|
|
96e4bd4eab | ||
|
|
d788afc126 | ||
|
|
50a7b1b9f5 | ||
|
|
79027970e1 | ||
|
|
6e9853add5 | ||
|
|
07f2dc8e8f | ||
|
|
0f924aebb0 | ||
|
|
8ec499ae3f | ||
|
|
53c1933ac8 | ||
|
|
4df3f775e1 | ||
|
|
6b570c573b | ||
|
|
d164749a7f | ||
|
|
50c5fd79f7 | ||
|
|
09288e9a1e |
No files matched your search
@@ -754,12 +754,17 @@ jobs:
|
||||
ln -sfn "$(cd "$jars" && pwd)" "$m2"
|
||||
echo "cache=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Cache Robolectric's Android jars
|
||||
- name: Restore Robolectric's Android jars
|
||||
id: robolectric-cache
|
||||
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: ../robolectric-jars
|
||||
key: robolectric-android-all-v2-${{ steps.robolectric.outputs.version }}
|
||||
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
|
||||
restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-
|
||||
- name: Count the restored Robolectric jars
|
||||
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||
run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV"
|
||||
- name: Unit tests
|
||||
id: unit-tests
|
||||
env:
|
||||
@@ -770,6 +775,34 @@ jobs:
|
||||
mkdir -p app/build
|
||||
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
|
||||
|
||||
# actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache.
|
||||
# Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first.
|
||||
- name: Save Robolectric's Android jars
|
||||
id: robolectric-jars-final
|
||||
if: always() && steps.robolectric-jars.outputs.cache == 'true'
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import glob, os, zipfile
|
||||
root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars')
|
||||
for f in glob.glob(os.path.join(root, '**', '*'), recursive=True):
|
||||
if not os.path.isfile(f):
|
||||
continue
|
||||
try:
|
||||
ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None
|
||||
except Exception:
|
||||
ok = False
|
||||
if not ok:
|
||||
os.remove(f)
|
||||
PY
|
||||
after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)
|
||||
[ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true
|
||||
- name: Store Robolectric's Android jars
|
||||
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: ../robolectric-jars
|
||||
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
|
||||
|
||||
- name: Upload unit test diagnostics
|
||||
id: unit-test-diagnostics
|
||||
if: always() && steps.unit-tests.outcome != 'skipped'
|
||||
|
||||
@@ -10,7 +10,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
|
||||
<p align="center"><b>100% open source. No ads. No Subscriptions. No telemetry. No proprietary components. No source withheld.</b></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.1%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.1"></a>
|
||||
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.11/DroidDeck-0.7.11.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.11%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.11"></a>
|
||||
<a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20us-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a>
|
||||
</p>
|
||||
|
||||
@@ -38,7 +38,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
|
||||
|
||||
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx, Mali, Xclipse and PowerVR are experimental. Adreno 710 is currently unsupported. No root needed.
|
||||
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
|
||||
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk), install the Linux runtime, press **Play** and sign in to Steam.
|
||||
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.11/DroidDeck-0.7.11.apk), install the Linux runtime, press **Play** and sign in to Steam.
|
||||
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
|
||||
|
||||
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
|
||||
@@ -68,6 +68,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
||||
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
||||
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
|
||||
- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT).
|
||||
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
||||
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
|
||||
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
||||
|
||||
@@ -620,7 +620,8 @@ static void cursor_publish_shown(void) {
|
||||
|
||||
static void cursor_publish_hidden(void) {
|
||||
pthread_mutex_lock(&g_cursor_lock);
|
||||
if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; }
|
||||
// A client that hides the cursor before ever showing one (gamescope drawing its own) must still be reported.
|
||||
if (!g_cursor_hidden || g_cursor_serial == 0) { g_cursor_hidden = 1; g_cursor_serial++; }
|
||||
pthread_mutex_unlock(&g_cursor_lock);
|
||||
}
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ class App : Application() {
|
||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.entries.map { it.id })
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.tabbed.map { it.id })
|
||||
com.droiddeck.launcher.update.AppUpdates.init(this)
|
||||
com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null))
|
||||
com.droiddeck.launcher.core.DownloadSource.init(this)
|
||||
@@ -80,6 +80,7 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.ea.EaBackend.app = this
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.rockstar.RockstarBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.steam.SteamBackend)
|
||||
}
|
||||
|
||||
private fun prefetchAddonPacks() {
|
||||
|
||||
@@ -141,6 +141,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var glThread by mutableStateOf(true)
|
||||
private var noGlError by mutableStateOf(true)
|
||||
private var returnAfterGame by mutableStateOf(true)
|
||||
private var valveProtonOnDemand by mutableStateOf(true)
|
||||
private var shaderPrecache by mutableStateOf<Boolean?>(null)
|
||||
private var steamRepairQueued by mutableStateOf(false)
|
||||
private var mangoapp by mutableStateOf(true)
|
||||
@@ -168,6 +169,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var battleNetInstalled by mutableStateOf(false)
|
||||
private var offlineAccount by mutableStateOf<String?>(null)
|
||||
private var offline by mutableStateOf(false)
|
||||
private var offlineAuto by mutableStateOf(true)
|
||||
private var showPerformance by mutableStateOf(false)
|
||||
private var clientOverride by mutableStateOf(false)
|
||||
private var clientCores by mutableStateOf<Set<Int>>(emptySet())
|
||||
@@ -1257,6 +1259,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
private fun startAfterSession(next: Intent) {
|
||||
if (com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(next)) {
|
||||
android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
SessionService.stop(this)
|
||||
awaitSessionEnd(next, android.os.SystemClock.uptimeMillis() + SESSION_SWITCH_WAIT_MS)
|
||||
}
|
||||
@@ -1343,6 +1349,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS)
|
||||
if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED)
|
||||
else registerReceiver(shortcutsInstallStatus, shortcutsFilter)
|
||||
if (GameLaunchIntent.accepts(intent.action) &&
|
||||
GameLaunchIntent.replayed(intent, savedInstanceState != null, savedInstanceState?.getString(STATE_PROCESS), PROCESS))
|
||||
clearGameLinkIntent(intent)
|
||||
readGameIntent(intent)
|
||||
// A Lab build is usually the agent's work, so the app comes back where the agent is.
|
||||
if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentTab.visible) navRequest = "agent"
|
||||
@@ -1415,7 +1424,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
gameSyncFolder = gameSyncFolder,
|
||||
busy = busy, stage = stage, percent = percent,
|
||||
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
|
||||
offlineAccount = offlineAccount, offline = offline,
|
||||
offlineAccount = offlineAccount, offline = offline, offlineAuto = offlineAuto,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
|
||||
enhancedDiagnosticsArmed = enhancedDiagnosticsArmed,
|
||||
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
|
||||
@@ -1753,6 +1762,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
OfflineMode.setEnabled(this, !OfflineMode.enabled(this))
|
||||
offline = OfflineMode.enabled(this)
|
||||
},
|
||||
onOfflineAuto = {
|
||||
OfflineMode.setAuto(this, !OfflineMode.auto(this))
|
||||
offlineAuto = OfflineMode.auto(this)
|
||||
offline = OfflineMode.enabled(this)
|
||||
},
|
||||
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
|
||||
onSoundtracksIngame = { on ->
|
||||
SessionPrefs.setSoundtracksIngame(this, on)
|
||||
@@ -2301,6 +2315,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
private fun saveLauncherState(outState: Bundle) {
|
||||
outState.putString(STATE_PROCESS, PROCESS)
|
||||
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
|
||||
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
|
||||
pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) }
|
||||
@@ -2384,6 +2399,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
|
||||
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
|
||||
defaultHomeLabel = HomeApp.defaultLabel(this)
|
||||
com.droiddeck.launcher.ui.NavTabs.syncHomeApps(this, homeAppSelected)
|
||||
refreshAndroidApps()
|
||||
integrationState = readIntegration()
|
||||
}
|
||||
@@ -2784,6 +2800,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
steamClientArch = if (mode == SessionService.MODE_STEAM) steamClientArch else null,
|
||||
returnAfterGame = if (mode == SessionService.MODE_STEAM) returnAfterGame else null,
|
||||
shaderPrecache = if (mode == SessionService.MODE_STEAM) shaderPrecache else null,
|
||||
valveProtonOnDemand = if (mode == SessionService.MODE_STEAM) valveProtonOnDemand else null,
|
||||
steamRepairQueued = steamRepairQueued,
|
||||
mangoapp = mangoapp,
|
||||
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
|
||||
@@ -2891,6 +2908,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
|
||||
onReturnAfterGame = { on -> SessionPrefs.setReturnAfterGame(this, on); returnAfterGame = on },
|
||||
onShaderPrecache = { on -> SessionPrefs.setShaderPrecache(this, on); shaderPrecache = on },
|
||||
onValveProtonOnDemand = { on -> SessionPrefs.setValveProtonOnDemand(this, on); valveProtonOnDemand = on },
|
||||
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
|
||||
onStartupSession = { id ->
|
||||
SessionPrefs.setStartupSession(this, id)
|
||||
@@ -3086,6 +3104,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
return
|
||||
}
|
||||
val target = com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return
|
||||
if (Library.fromSteamClient(g)) {
|
||||
com.droiddeck.launcher.stores.steam.SteamStore.uninstall(this, g.appId, target.manifest, fallback = { com.droiddeck.launcher.frontend.GameRemoval.delete(target) }) { refreshAddedGames(); refresh() }
|
||||
return
|
||||
}
|
||||
Thread({
|
||||
com.droiddeck.launcher.frontend.GameRemoval.delete(target)
|
||||
ui.post { refreshAddedGames(); refresh() }
|
||||
@@ -3163,6 +3185,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
steamRepairQueued = SteamRepair.queued(this)
|
||||
mangoapp = SessionPrefs.mangoapp(this)
|
||||
returnAfterGame = SessionPrefs.returnAfterGame(this)
|
||||
valveProtonOnDemand = SessionPrefs.valveProtonOnDemand(this)
|
||||
loadShaderPrecache(mode)
|
||||
steamController = SessionPrefs.steamController(this)
|
||||
startupSession = SessionPrefs.startupSession(this)
|
||||
@@ -3314,6 +3337,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
battleNetInstalled = com.droiddeck.launcher.runtime.BattleNet.installed(this)
|
||||
offlineAccount = OfflineMode.account(this)
|
||||
offline = OfflineMode.enabled(this)
|
||||
offlineAuto = OfflineMode.auto(this)
|
||||
installed = LinuxRuntimeInstaller.installedVersion(this)
|
||||
ready = LinuxRuntime.isInstalled(this)
|
||||
vkBridge = SessionPrefs.vkBridge(this)
|
||||
@@ -3459,6 +3483,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
if (!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(intent)) {
|
||||
android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
refreshPhantomStatus()
|
||||
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
if (queueIfBlocked) queuedLaunch.queue(intent, System.currentTimeMillis())
|
||||
@@ -3521,9 +3549,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
retryMs = GATE_LAUNCH_RETRY_MS,
|
||||
)
|
||||
|
||||
/** The conditions under which a Steam start waits instead of being refused: setup, a runtime or desktop install, or a storage cleanup. */
|
||||
/** The conditions under which a Steam start waits instead of being refused: setup, a runtime or desktop install, a storage cleanup, or a Steam store download. */
|
||||
private fun steamStartBusy(): Boolean = busy || LinuxRuntimeInstaller.isBusy() || com.droiddeck.launcher.session.Onboarding.settling() ||
|
||||
(SessionState.installing != null && !SessionState.running) || com.droiddeck.launcher.storage.StorageState.cleaning
|
||||
(SessionState.installing != null && !SessionState.running) || com.droiddeck.launcher.storage.StorageState.cleaning ||
|
||||
(!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.downloading())
|
||||
|
||||
private fun refreshPhantomStatus() {
|
||||
phantomProcessStatus = PhantomProcessLimit.read(this)
|
||||
@@ -3659,6 +3688,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val PROCESS = java.util.UUID.randomUUID().toString()
|
||||
private const val STATE_PROCESS = "process"
|
||||
private const val REQUEST_NOTIFICATIONS = 7103
|
||||
private const val EXTRA_RESTARTED = "com.droiddeck.launcher.extra.RESTARTED"
|
||||
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
|
||||
|
||||
@@ -49,7 +49,7 @@ internal class ProtonMenu(
|
||||
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
|
||||
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
|
||||
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
|
||||
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
|
||||
{ tool, progress -> ProtonExtras.install(activity, tool, onProgress = progress) }
|
||||
|
||||
fun installProton(id: String, automatic: Boolean = false) {
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
|
||||
@@ -842,6 +842,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
finish()
|
||||
return
|
||||
}
|
||||
if (!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(intent)) {
|
||||
runtimeRemovalBlocked = true
|
||||
android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show()
|
||||
finish()
|
||||
return
|
||||
}
|
||||
if (savedInstanceState == null && !SessionState.running && !com.droiddeck.launcher.stores.steam.SteamStore.downloading()) {
|
||||
// The Steam client signs in itself; the store's own sign-in must not overlap it.
|
||||
Thread({ com.droiddeck.launcher.stores.steam.SteamEngine.forget() }, "steam-store-signout").start()
|
||||
}
|
||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||
@@ -2834,6 +2844,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun installProton(): String? {
|
||||
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
|
||||
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(this)) return installOwnProton()
|
||||
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
@@ -2846,6 +2857,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
}
|
||||
|
||||
private fun installOwnProton(): String? {
|
||||
val extras = com.droiddeck.launcher.session.ProtonExtras
|
||||
while ((extras.prefetching || extras.installInProgress) && !SessionState.stopRequested) {
|
||||
try { Thread.sleep(250) } catch (_: InterruptedException) { Thread.currentThread().interrupt(); return "interrupted" }
|
||||
}
|
||||
if (SessionState.stopRequested) return "cancelled"
|
||||
if (!com.droiddeck.launcher.runtime.DesktopCatalog.ownProtonMissing(this)) return null
|
||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
return try {
|
||||
extras.install(this, extras.tools.first { it.id == extras.OWN }, cancellation) { label, percent ->
|
||||
uiHandler.post { loading.percent = percent; loading.say(label, PROTON_LINES.topic, readable = true) }
|
||||
}.also { if (it == null) com.droiddeck.launcher.session.Onboarding.recheck(this) }
|
||||
} finally {
|
||||
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
|
||||
}
|
||||
}
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
if (holder !== outputHolder()) return
|
||||
if (installingRuntime || SessionState.stopRequested || ended) return
|
||||
@@ -3395,8 +3424,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (status == 0) SessionState.takeRelaunch()?.let { next ->
|
||||
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
|
||||
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
|
||||
setIntent(next)
|
||||
recreate()
|
||||
relaunch(next)
|
||||
return@runOnUiThread
|
||||
}
|
||||
showEnded(status, hint)
|
||||
@@ -3404,6 +3432,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}, "session-end-hint").start()
|
||||
}
|
||||
|
||||
// recreate() keeps this window, and Compose content added to it afterwards never recomposes, so the
|
||||
// loading screen of the next session stays up over a running session. A new instance gets its own window.
|
||||
// This instance finishes first because the activity is singleTask and would otherwise take the intent itself.
|
||||
private fun relaunch(next: Intent) {
|
||||
closeAtOnce = true
|
||||
super.finish()
|
||||
startActivity(next)
|
||||
overridePendingTransition(0, 0)
|
||||
}
|
||||
|
||||
private fun showEnded(status: Int, hint: EndHint?) {
|
||||
if (status == 0 && hint?.evenOnSuccess != true) {
|
||||
finish()
|
||||
@@ -6031,8 +6069,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
Log.w(TAG, "ignoring agent start while session phase is ${SessionState.phase}")
|
||||
return
|
||||
}
|
||||
setIntent(intent)
|
||||
recreate()
|
||||
relaunch(android.content.Intent(intent).setClass(this, SessionActivity::class.java))
|
||||
return
|
||||
}
|
||||
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
|
||||
|
||||
@@ -293,6 +293,7 @@ object DeviceReport {
|
||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||
k("Avoid notch", SessionPrefs.avoidNotch(context))
|
||||
k("Return to launcher after a game", SessionPrefs.returnAfterGame(context))
|
||||
k("Valve Proton only when needed", SessionPrefs.valveProtonOnDemand(context))
|
||||
k("Microphone", SessionPrefs.micEnabled(context))
|
||||
k("On-screen controls", SessionPrefs.oscMode(context))
|
||||
k("Touch mode", SessionPrefs.touchMode(context))
|
||||
|
||||
@@ -11,6 +11,10 @@ object GameLaunchIntent {
|
||||
|
||||
fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION
|
||||
|
||||
fun replayed(intent: Intent, restored: Boolean, savedProcess: String?, process: String): Boolean =
|
||||
!(intent.data?.scheme == "droiddeck" && intent.data?.host == "settings") &&
|
||||
(intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0 || restored && savedProcess != process)
|
||||
|
||||
fun read(context: Context, intent: Intent): GameRequest? = when (intent.action) {
|
||||
Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent)
|
||||
ACTION, GAMENATIVE_ACTION -> readExtras(intent)
|
||||
|
||||
@@ -7,17 +7,21 @@ object SocNames {
|
||||
"SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870",
|
||||
"SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1",
|
||||
"SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3",
|
||||
"SM8635" to "Snapdragon 8s Gen 3", "SM8735" to "Snapdragon 8s Gen 4",
|
||||
"SM8750" to "Snapdragon 8 Elite", "SM8750P" to "Snapdragon 8 Elite",
|
||||
"SM8850" to "Snapdragon 8 Elite Gen 5",
|
||||
"SM8975" to "Snapdragon 8 Elite Extreme Gen 6",
|
||||
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
|
||||
"SM7675" to "Snapdragon 7+ Gen 3",
|
||||
"SM6375" to "Snapdragon 695",
|
||||
// Handheld parts: AYANEO Pocket FIT (SG8350P), Retroid Pocket Duo (CQ7790S).
|
||||
"SG8350P" to "Snapdragon G3 Gen 3", "CQ7790S" to "Dragonwing Q-7790",
|
||||
)
|
||||
|
||||
private val PLATFORMS = mapOf(
|
||||
"msmnile" to "Snapdragon 855/860", "kona" to "Snapdragon 865/870", "lahaina" to "Snapdragon 888",
|
||||
"taro" to "Snapdragon 8 Gen 1", "cape" to "Snapdragon 8+ Gen 1", "kalama" to "Snapdragon 8 Gen 2",
|
||||
"pineapple" to "Snapdragon 8 Gen 3", "sun" to "Snapdragon 8 Elite",
|
||||
"pineapple" to "Snapdragon 8 Gen 3", "sun" to "Snapdragon 8 Elite", "canoe" to "Snapdragon 8 Elite Gen 5",
|
||||
)
|
||||
|
||||
fun model(prop: (String) -> String = GpuInfo::systemProperty): String {
|
||||
@@ -30,8 +34,23 @@ object SocNames {
|
||||
|
||||
internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim()
|
||||
|
||||
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? =
|
||||
MODELS[normalizedModel(model)] ?: PLATFORMS[platform.lowercase()]?.let { "$it family" }
|
||||
/**
|
||||
* The exact model's name; the board platform's family only for an empty model or a phone "SM" part, since
|
||||
* different chips share a platform (the Retroid Pocket Duo's CQ7790S and the Snapdragon 8 Elite are both "sun").
|
||||
*/
|
||||
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? {
|
||||
val m = normalizedModel(model)
|
||||
MODELS[m]?.let { return it }
|
||||
if (m.isNotEmpty() && !m.startsWith("SM")) return null
|
||||
return PLATFORMS[platform.lowercase()]?.let { "$it family" }
|
||||
}
|
||||
|
||||
// Without label's platform-family guess: a rebadged chip such as the Duo's CQ7790S reports a platform it is not.
|
||||
fun plainName(model: String = model(), maker: String = manufacturer()): String =
|
||||
MODELS[normalizedModel(model)]?.let { "$it ($model)" } ?: "$maker $model".trim()
|
||||
|
||||
private fun manufacturer(): String =
|
||||
if (Build.VERSION.SDK_INT >= 31) Build.SOC_MANUFACTURER.takeIf { it != Build.UNKNOWN }.orEmpty() else ""
|
||||
|
||||
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
|
||||
val name = name(model, platform)
|
||||
|
||||
@@ -273,7 +273,8 @@ public final class PadBridge {
|
||||
static boolean isSystemVirtualInputName(String name) {
|
||||
if (name == null) return false;
|
||||
String lower = name.trim().toLowerCase(java.util.Locale.ROOT);
|
||||
return lower.startsWith("uinput-") || lower.startsWith("uinput_");
|
||||
// Xiaomi's "ui-input-xiaomi" is a system uinput device that also reports gamepad sources.
|
||||
return lower.startsWith("uinput-") || lower.startsWith("uinput_") || lower.equals("ui-input-xiaomi");
|
||||
}
|
||||
|
||||
public static boolean isFromController(InputDevice device) {
|
||||
|
||||
@@ -90,13 +90,16 @@ object CurseForgeApp {
|
||||
return out;
|
||||
})()"""
|
||||
|
||||
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
|
||||
private val CORE = JSONObject.quote("CoreService")
|
||||
|
||||
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r", connect: Boolean = true): String {
|
||||
val name = JSONObject.quote(method)
|
||||
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
|
||||
val key = JSONObject.quote(service)
|
||||
val link = if (connect && args != null) "const c = m[$CORE]; if (!c || typeof c.connect !== 'function') return { missing: true }; await c.connect(); " else ""
|
||||
val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " +
|
||||
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
|
||||
"return { value: $run }; })()"
|
||||
link + "return { value: $run }; })()"
|
||||
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
|
||||
".find(w => !w.isDestroyed() && w.webContents.getURL().includes('desktop.html')); " +
|
||||
"if (!w) return JSON.stringify({ missing: true }); " +
|
||||
@@ -173,7 +176,6 @@ object CurseForgeApp {
|
||||
}
|
||||
|
||||
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
|
||||
private val connected = ConcurrentHashMap.newKeySet<String>()
|
||||
|
||||
private fun lines(context: Context, argv: List<String>): List<String> {
|
||||
val out = ArrayList<String>()
|
||||
@@ -181,8 +183,8 @@ object CurseForgeApp {
|
||||
return out
|
||||
}
|
||||
|
||||
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? =
|
||||
unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick), timeoutMs))) ?: throw Failure("CurseForge gave no answer"))
|
||||
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r", connect: Boolean = true): Any? =
|
||||
unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick, connect), timeoutMs))) ?: throw Failure("CurseForge gave no answer"))
|
||||
|
||||
private sealed class Launch {
|
||||
class Url(val inspector: String) : Launch()
|
||||
@@ -234,24 +236,16 @@ object CurseForgeApp {
|
||||
hold.set(true)
|
||||
return
|
||||
}
|
||||
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
|
||||
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true", connect = false) }
|
||||
hold.set(true)
|
||||
inspector?.let(connected::remove)
|
||||
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
|
||||
}
|
||||
|
||||
private fun connect(context: Context, inspector: String) {
|
||||
if (inspector in connected) return
|
||||
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
|
||||
connected += inspector
|
||||
}
|
||||
|
||||
private fun instances(context: Context, inspector: String): Any? =
|
||||
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
|
||||
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 120_000,
|
||||
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
|
||||
|
||||
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
|
||||
connect(context, inspector)
|
||||
instanceFor(instances(context, inspector), flavorDir, null)?.let { return it }
|
||||
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
|
||||
return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
|
||||
@@ -261,7 +255,6 @@ object CurseForgeApp {
|
||||
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
|
||||
|
||||
fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List<Project> {
|
||||
connect(context, inspector)
|
||||
if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000)
|
||||
return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS))
|
||||
}
|
||||
@@ -283,19 +276,16 @@ object CurseForgeApp {
|
||||
}
|
||||
|
||||
fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||
connect(context, inspector)
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
|
||||
}
|
||||
|
||||
fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||
connect(context, inspector)
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? {
|
||||
connect(context, inspector)
|
||||
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
|
||||
if (failed == null || failed.length() > 0) return null
|
||||
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
|
||||
|
||||
@@ -109,9 +109,15 @@ object DesktopCatalog {
|
||||
FileUtils.readString(marker(context, id))?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
fun protonSeedNeeded(context: Context): Boolean =
|
||||
installed(context, PROTON_SEED_ID) == null &&
|
||||
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(context)) ownProtonMissing(context)
|
||||
else installed(context, PROTON_SEED_ID) == null &&
|
||||
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
|
||||
|
||||
fun ownProtonMissing(context: Context): Boolean {
|
||||
val extras = com.droiddeck.launcher.session.ProtonExtras
|
||||
return extras.installedAll(context, extras.tools.first { it.id == extras.OWN }).isEmpty()
|
||||
}
|
||||
|
||||
const val DESKTOP_ID = "desktop-kde"
|
||||
const val EMULATORS_ID = "emulators"
|
||||
private const val EMULATORS_SCRIPT = "/usr/local/bin/droiddeck-emulators"
|
||||
|
||||
@@ -199,6 +199,7 @@ public final class LinuxRuntime {
|
||||
}
|
||||
|
||||
public static List<String> prootPrefix(Context context, File root, String cwd, boolean fakeRoot) {
|
||||
NativeGuest.relinkAfterProot(root);
|
||||
List<String> cmd = new ArrayList<>();
|
||||
cmd.addAll(com.droiddeck.launcher.core.HostProcess.dataExecutable(prootBinary(context).getPath()));
|
||||
cmd.add("--kill-on-exit");
|
||||
|
||||
@@ -169,8 +169,15 @@ object NativeGuest {
|
||||
}
|
||||
}
|
||||
|
||||
private const val RELINK_STAMP = "etc/droiddeck/native-symlinks"
|
||||
|
||||
@JvmStatic
|
||||
fun relinkAfterProot(root: File) {
|
||||
File(root, RELINK_STAMP).delete()
|
||||
}
|
||||
|
||||
private val HOST_LINK_TARGETS = listOf("/proc", "/dev", "/sys", "/sdcard", "/storage", "/data", "/system", "/vendor", "/apex",
|
||||
"/system_ext", "/product", "/odm", "/linkerconfig", "/mnt")
|
||||
"/system_ext", "/product", "/odm", "/linkerconfig", "/mnt", "/root/Storage")
|
||||
|
||||
/**
|
||||
* Symbolic links the kernel follows by itself (ld.so, Steam, anything that skips the hook) read
|
||||
@@ -178,9 +185,9 @@ object NativeGuest {
|
||||
* which reads the target inside the rootfs, so each is rewritten as a relative link, which
|
||||
* resolves the same way under proot and without it. Rerun when the runtime changes.
|
||||
*/
|
||||
fun relinkAbsoluteSymlinks(context: Context, root: File): Int {
|
||||
val stamp = File(root, "etc/droiddeck/native-symlinks")
|
||||
val version = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(context).orEmpty() + "/2"
|
||||
fun relinkAbsoluteSymlinks(context: Context, root: File, commands: () -> Sequence<List<String>> = ::procCommands): Int {
|
||||
val stamp = File(root, RELINK_STAMP)
|
||||
val version = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(context).orEmpty() + "/3"
|
||||
if (stamp.isFile && stamp.readText() == version) return 0
|
||||
val rootPath = root.toPath()
|
||||
var rewritten = 0
|
||||
@@ -206,11 +213,20 @@ object NativeGuest {
|
||||
|
||||
override fun visitFileFailed(file: java.nio.file.Path, exc: java.io.IOException) = java.nio.file.FileVisitResult.CONTINUE
|
||||
})
|
||||
stamp.parentFile?.mkdirs()
|
||||
stamp.writeText(version)
|
||||
if (!prootRunning(LinuxRuntime.prootBinary(context).path, commands())) {
|
||||
stamp.parentFile?.mkdirs()
|
||||
stamp.writeText(version)
|
||||
}
|
||||
return rewritten
|
||||
}
|
||||
|
||||
internal fun prootRunning(proot: String, commands: Sequence<List<String>>): Boolean =
|
||||
commands.any { args -> args.take(2).any { it == proot } }
|
||||
|
||||
private fun procCommands(): Sequence<List<String>> = (File("/proc").listFiles() ?: emptyArray()).asSequence()
|
||||
.filter { it.name.all(Char::isDigit) }
|
||||
.mapNotNull { runCatching { File(it, "cmdline").readText().split('\u0000') }.getOrNull() }
|
||||
|
||||
/**
|
||||
* The guest path that host path [target] stands for in a session with [binds] ("src:dst"), or null
|
||||
* when it is a guest path already: the rootfs, or the longest mount source holding it (the first
|
||||
|
||||
@@ -22,7 +22,7 @@ class RuntimeInstallService : Service() {
|
||||
if (intent?.action == ACTION_PACKAGE) return holdPackage(startId)
|
||||
val removal = intent?.action == ACTION_REMOVE
|
||||
val release = intent?.let(::releaseFrom)
|
||||
startForeground(NOTIFICATION_ID, notification(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
|
||||
val foreground = enterForeground(notification(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
|
||||
if (release == null && !removal) {
|
||||
stopSelf(startId)
|
||||
return START_NOT_STICKY
|
||||
@@ -31,7 +31,7 @@ class RuntimeInstallService : Service() {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
var shown = ""
|
||||
val progress = LinuxRuntimeInstaller.ProgressListener { stage, percent ->
|
||||
if ("$stage:$percent" != shown) {
|
||||
if (foreground && "$stage:$percent" != shown) {
|
||||
shown = "$stage:$percent"
|
||||
manager?.notify(NOTIFICATION_ID, notification(stage, percent))
|
||||
}
|
||||
@@ -46,7 +46,10 @@ class RuntimeInstallService : Service() {
|
||||
}
|
||||
|
||||
private fun holdPackage(startId: Int): Int {
|
||||
startForeground(NOTIFICATION_ID, notification(packageStage, packagePercent, packageTitle))
|
||||
if (!enterForeground(notification(packageStage, packagePercent, packageTitle))) {
|
||||
stopSelf(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
Thread({
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
var shown = ""
|
||||
@@ -65,6 +68,15 @@ class RuntimeInstallService : Service() {
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
/** Android 12+ refuses a foreground start while the app is in the background; the work then goes on without the notification. */
|
||||
private fun enterForeground(notification: Notification): Boolean = try {
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
true
|
||||
} catch (e: IllegalStateException) {
|
||||
android.util.Log.w("RuntimeInstallService", "running without a foreground service: $e")
|
||||
false
|
||||
}
|
||||
|
||||
private fun notification(stage: String, percent: Int, title: String? = null): Notification {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.setup_runtime),
|
||||
|
||||
@@ -2,16 +2,20 @@ package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.agent.AgentGuest
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
object OfflineMode {
|
||||
private const val TAG = "OfflineMode"
|
||||
private const val KEY = "steam_offline"
|
||||
private const val AUTO_KEY = "steam_offline_auto"
|
||||
private const val NETWORK_KEY = "steam_offline_by_network"
|
||||
private val WANTS = Regex("""^(\s*"WantsOfflineMode"\s*")([01])(".*)$""")
|
||||
private val SKIP = Regex("""^(\s*"SkipOfflineModeWarning"\s*")([01])(".*)$""")
|
||||
private val REMEMBER = Regex(""""RememberPassword"\s*"1"""")
|
||||
private val PERSONA = Regex(""""PersonaName"\s*"([^"]*)"""")
|
||||
private const val EVAL_TIMEOUT_MS = 10_000L
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
@@ -19,10 +23,12 @@ object OfflineMode {
|
||||
|
||||
private fun x64LoginUsers(root: File) = File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf")
|
||||
|
||||
fun account(context: Context): String? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val file = x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
|
||||
private fun activeLoginUsers(context: Context, root: File) =
|
||||
x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
|
||||
?: loginUsers(root)
|
||||
|
||||
fun account(context: Context): String? {
|
||||
val file = activeLoginUsers(context, LinuxRuntime.rootDir(context))
|
||||
val text = try {
|
||||
if (file.isFile) file.readText() else return null
|
||||
} catch (e: Exception) {
|
||||
@@ -32,21 +38,114 @@ object OfflineMode {
|
||||
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() }.orEmpty()
|
||||
}
|
||||
|
||||
fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false)
|
||||
private fun steamWants(context: Context, root: File): Boolean? {
|
||||
val file = activeLoginUsers(context, root)
|
||||
val lines = try {
|
||||
if (file.isFile) file.readLines() else return null
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not read loginusers.vdf", e); return null
|
||||
}
|
||||
val values = lines.mapNotNull { WANTS.matchEntire(it)?.groupValues?.get(2) }
|
||||
return if (values.isEmpty()) null else "1" in values
|
||||
}
|
||||
|
||||
internal fun manual(steamWants: Boolean?, automatic: Boolean, saved: Boolean): Boolean =
|
||||
if (steamWants == null) saved else steamWants && !automatic
|
||||
|
||||
internal fun offline(manual: Boolean, online: Boolean, auto: Boolean = true): Boolean = manual || (auto && !online)
|
||||
|
||||
internal fun afterNetworkChange(manual: Boolean, online: Boolean): Boolean = manual && !online
|
||||
|
||||
fun auto(context: Context): Boolean = prefs(context).getBoolean(AUTO_KEY, true)
|
||||
|
||||
fun enabled(context: Context): Boolean = saved(context, LinuxRuntime.rootDir(context))
|
||||
|
||||
fun active(context: Context): Boolean =
|
||||
offline(enabled(context), isOnline(context), auto(context))
|
||||
|
||||
@Synchronized
|
||||
fun setEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean(KEY, on).apply()
|
||||
apply(context, LinuxRuntime.rootDir(context))
|
||||
write(context, LinuxRuntime.rootDir(context), on)
|
||||
SteamOfflineFollow.request()
|
||||
}
|
||||
|
||||
fun apply(context: Context, root: File) {
|
||||
applyTo(context, loginUsers(root))
|
||||
applyTo(context, x64LoginUsers(root))
|
||||
@Synchronized
|
||||
fun setAuto(context: Context, on: Boolean) {
|
||||
val manual = if (on) false else steamWants(context, LinuxRuntime.rootDir(context)) ?: active(context)
|
||||
prefs(context).edit().putBoolean(AUTO_KEY, on).commit()
|
||||
setEnabled(context, manual)
|
||||
}
|
||||
|
||||
private fun applyTo(context: Context, file: File) {
|
||||
fun apply(context: Context, root: File): Boolean = write(context, root, saved(context, root))
|
||||
|
||||
fun sync(context: Context): Boolean? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val offline = synchronized(this) { write(context, root, saved(context, root)) }
|
||||
return switchLive(context, offline)
|
||||
}
|
||||
|
||||
fun follow(context: Context): Boolean? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val (byNetwork, offline) = synchronized(this) {
|
||||
if (!auto(context)) return false
|
||||
prefs(context).getBoolean(NETWORK_KEY, false) to
|
||||
write(context, root, afterNetworkChange(saved(context, root), isOnline(context)))
|
||||
}
|
||||
val result = switchLive(context, offline)
|
||||
if (result == null && !offline && byNetwork) restoreNetworkOffline(context)
|
||||
return result
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
internal fun restoreNetworkOffline(context: Context) {
|
||||
val prefs = prefs(context)
|
||||
if (!auto(context) || prefs.getBoolean(KEY, false) || prefs.getBoolean(NETWORK_KEY, false)) return
|
||||
prefs.edit().putBoolean(NETWORK_KEY, true).apply()
|
||||
}
|
||||
|
||||
private fun isOnline(context: Context) = com.droiddeck.launcher.frontend.AutoComponents.isOnline(context)
|
||||
|
||||
private fun saved(context: Context, root: File): Boolean {
|
||||
val prefs = prefs(context)
|
||||
return manual(steamWants(context, root), prefs.getBoolean(NETWORK_KEY, false), prefs.getBoolean(KEY, false))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun remember(context: Context, manual: Boolean): Boolean {
|
||||
val online = isOnline(context)
|
||||
val auto = auto(context)
|
||||
val offline = offline(manual, online, auto)
|
||||
prefs(context).edit().putBoolean(KEY, manual).putBoolean(NETWORK_KEY, offline && !manual).apply()
|
||||
Log.i(TAG, "auto=$auto manual=$manual online=$online offline=$offline")
|
||||
return offline
|
||||
}
|
||||
|
||||
private fun switchLive(context: Context, offline: Boolean): Boolean? {
|
||||
val answer = try {
|
||||
AgentGuest.steamEval(context, "$SWITCH($offline)", EVAL_TIMEOUT_MS)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "steam not reachable: ${e.javaClass.simpleName}: ${e.message}")
|
||||
return null
|
||||
}
|
||||
val result = if (answer.optBoolean("ok")) answer.optString("value") else answer.optJSONObject("error")?.optString("message")
|
||||
Log.i(TAG, "live offline=$offline: $result")
|
||||
return when (result) {
|
||||
"switched" -> true
|
||||
"same" -> false
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun write(context: Context, root: File, manual: Boolean): Boolean {
|
||||
val offline = remember(context, manual)
|
||||
applyTo(loginUsers(root), offline)
|
||||
applyTo(x64LoginUsers(root), offline)
|
||||
return offline
|
||||
}
|
||||
|
||||
private fun applyTo(file: File, offline: Boolean) {
|
||||
if (!file.isFile) return
|
||||
val want = if (enabled(context)) "1" else "0"
|
||||
val want = if (offline) "1" else "0"
|
||||
try {
|
||||
val lines = file.readLines()
|
||||
val out = ArrayList<String>(lines.size + 4)
|
||||
@@ -94,4 +193,25 @@ object OfflineMode {
|
||||
Log.w(TAG, "could not write loginusers.vdf", e)
|
||||
}
|
||||
}
|
||||
|
||||
private val SWITCH = """(async want => {
|
||||
const user = globalThis.SteamClient?.User;
|
||||
if (typeof user?.GoOffline !== 'function' || typeof user?.GoOnline !== 'function') return "missing";
|
||||
const seen = globalThis.__droiddeckSteamOffline ??= { value: null };
|
||||
seen.want = want;
|
||||
if (!seen.registered) {
|
||||
seen.registered = true;
|
||||
user.RegisterForCurrentUserChanges(u => { seen.value = !!u?.bIsOfflineMode; });
|
||||
globalThis.SteamClient.GameSessions?.RegisterForAppLifetimeNotifications?.(n => {
|
||||
if (n?.bRunning) return;
|
||||
setTimeout(() => { if (seen.want === true && seen.value === false) user.GoOffline(); }, 2000);
|
||||
});
|
||||
}
|
||||
for (let waited = 0; seen.value === null && waited < 4000; waited += 100) await new Promise(done => setTimeout(done, 100));
|
||||
const current = seen.value;
|
||||
if (current === null) return "unknown";
|
||||
if (current === want) return "same";
|
||||
if (want) user.GoOffline(); else user.GoOnline();
|
||||
return "switched";
|
||||
})"""
|
||||
}
|
||||
@@ -249,21 +249,24 @@ object ProtonExtras {
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
fun install(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier? = null,
|
||||
onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
|
||||
installInProgress = true
|
||||
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
|
||||
return try { installNow(context, tool, cancelled, onProgress) } finally { installInProgress = false }
|
||||
}
|
||||
|
||||
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? {
|
||||
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit,
|
||||
cancelled: java.util.function.BooleanSupplier? = null): String? {
|
||||
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
|
||||
onProgress(downloading, 0)
|
||||
var downloaded = false
|
||||
for (attempt in 0 until 5) {
|
||||
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256) { fraction ->
|
||||
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256, cancelled) { fraction ->
|
||||
onProgress(downloading, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
|
||||
}
|
||||
if (downloaded) break
|
||||
if (cancelled?.asBoolean == true) return context.getString(R.string.pextra_interrupted)
|
||||
if (attempt < 4) {
|
||||
onProgress(context.getString(R.string.pextra_retrying, attempt + 2, 5), -1)
|
||||
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
|
||||
@@ -297,7 +300,8 @@ object ProtonExtras {
|
||||
return problem
|
||||
}
|
||||
|
||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
private fun installNow(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier?,
|
||||
onProgress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||
|
||||
@@ -312,7 +316,7 @@ object ProtonExtras {
|
||||
|
||||
val checked = asset.sha256 != null && asset.size > 0 && checkedArchive == fingerprint(archive) &&
|
||||
checkedDigest.equals(asset.sha256, ignoreCase = true)
|
||||
if (!checked) fetchArchive(context, tool, asset, archive, onProgress)?.let { return it }
|
||||
if (!checked) fetchArchive(context, tool, asset, archive, onProgress, cancelled)?.let { return it }
|
||||
if (asset.size > 0 && archive.length() != asset.size) {
|
||||
if (archive.length() > asset.size) {
|
||||
archive.delete()
|
||||
|
||||
@@ -28,12 +28,14 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-bottom-desktop" to "usr/local/bin/droiddeck-bottom-desktop",
|
||||
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
|
||||
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
|
||||
"usr/local/bin/droiddeck-device-info" to "usr/local/bin/droiddeck-device-info",
|
||||
"usr/local/bin/droiddeck-desktop-window-rules" to "usr/local/bin/droiddeck-desktop-window-rules",
|
||||
"usr/local/bin/droiddeck-library-perms" to "usr/local/bin/droiddeck-library-perms",
|
||||
"usr/local/bin/droiddeck-ime" to "usr/local/bin/droiddeck-ime",
|
||||
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
|
||||
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
|
||||
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
|
||||
"etc/xdg/fastfetch/config.jsonc" to "etc/xdg/fastfetch/config.jsonc",
|
||||
)
|
||||
|
||||
private val SERVICE_PACKS = mapOf(
|
||||
|
||||
@@ -448,6 +448,13 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
|
||||
}
|
||||
|
||||
fun appsTabHomeSeen(context: Context): Boolean? =
|
||||
prefs(context).takeIf { it.contains("appsTabHomeSeen") }?.getBoolean("appsTabHomeSeen", false)
|
||||
|
||||
fun setAppsTabHomeSeen(context: Context, seen: Boolean) {
|
||||
prefs(context).edit().putBoolean("appsTabHomeSeen", seen).apply()
|
||||
}
|
||||
|
||||
private fun idList(raw: String?): List<String> = raw.orEmpty().split(',').map { it.trim() }.filter { it.isNotEmpty() }
|
||||
|
||||
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
|
||||
@@ -838,6 +845,15 @@ object SessionPrefs {
|
||||
|
||||
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
|
||||
|
||||
fun valveProtonOnDemand(context: Context): Boolean = prefs(context).getBoolean("valveProtonOnDemand", true)
|
||||
|
||||
fun setValveProtonOnDemand(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("valveProtonOnDemand", on).apply()
|
||||
}
|
||||
|
||||
/** DroidDeck-Proton is the Proton placed before the client starts; Valve's ARM64 Proton waits for a title that needs it. */
|
||||
fun ownProtonFirst(context: Context): Boolean = valveProtonOnDemand(context) && !ProtonExtras.declined(context)
|
||||
|
||||
fun setReturnAfterGame(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("returnAfterGame", on).apply()
|
||||
}
|
||||
|
||||
@@ -669,6 +669,8 @@ class SessionService : Service() {
|
||||
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
|
||||
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
|
||||
guest.add("DD_REFRESH=" + Math.round(SessionState.refreshHz))
|
||||
guest.add("DD_DEVICE_NAME=" + android.os.Build.MODEL)
|
||||
com.droiddeck.launcher.gpu.SocNames.plainName().takeIf { it.isNotEmpty() }?.let { guest.add("DD_SOC_NAME=$it") }
|
||||
guest.add("DD_LOG=" + sessionLog.path)
|
||||
guest.add("DD_DEBUG_DIR=" + sessionDir.path)
|
||||
if (EnhancedDiagnostics.isActive(this, sessionDir)) guest.add("DROIDDECK_ENHANCED_DIAGNOSTICS=1")
|
||||
@@ -694,7 +696,7 @@ class SessionService : Service() {
|
||||
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
|
||||
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
|
||||
guest.add("DD_ADDED_GAMES=" + listing.path)
|
||||
if (OfflineMode.enabled(this)) guest.add("DD_STEAM_OFFLINE=1")
|
||||
if (OfflineMode.active(this)) guest.add("DD_STEAM_OFFLINE=1")
|
||||
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
|
||||
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
|
||||
}
|
||||
@@ -813,6 +815,11 @@ class SessionService : Service() {
|
||||
.onFailure { Log.w(TAG, "desktop language pack: $it") }
|
||||
}
|
||||
|
||||
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) {
|
||||
val steamOffline = SteamOfflineFollow()
|
||||
steamOffline.attach(this)
|
||||
components.add(steamOffline)
|
||||
}
|
||||
val networkLink = LinuxNetworkLinkComponent(this, root)
|
||||
networkLink.attach(this)
|
||||
networkLink.publish()
|
||||
@@ -1002,6 +1009,7 @@ class SessionService : Service() {
|
||||
))
|
||||
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
|
||||
if (SessionState.mode == MODE_STEAM) SessionPrefs.pendingShaderPrecache(this)?.let { guest.add("DD_SHADER_PRECACHE=" + if (it) "1" else "0") }
|
||||
guest.add("DD_VALVE_PROTON=" + if (SessionPrefs.ownProtonFirst(this)) "0" else "1")
|
||||
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
|
||||
guest.add("XDG_SESSION_TYPE=wayland")
|
||||
guest.add("WAYLAND_DISPLAY=wayland-0")
|
||||
|
||||
@@ -25,7 +25,7 @@ object SettingsReset {
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "blackFrameInsertion", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
|
||||
"steamDownloadsInBackground", "steam_offline", "steam_offline_auto", "steam_offline_by_network", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen", "bootMovieShuffle",
|
||||
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
|
||||
)
|
||||
@@ -67,7 +67,7 @@ object SettingsReset {
|
||||
}
|
||||
|
||||
QuestExperimental.initialize(context)
|
||||
runCatching { OfflineMode.apply(context, LinuxRuntime.rootDir(context)) }
|
||||
runCatching { OfflineMode.setEnabled(context, false) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not turn offline mode off", it) }
|
||||
runCatching { GameEnvironmentStore.publish(context) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not update game environment", it) }
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import com.droiddeck.launcher.frontend.AutoComponents
|
||||
|
||||
class SteamOfflineFollow : SessionPart() {
|
||||
private var thread: HandlerThread? = null
|
||||
@Volatile private var handler: Handler? = null
|
||||
private var callback: ConnectivityManager.NetworkCallback? = null
|
||||
private var online: Boolean? = null
|
||||
private var retries = 0
|
||||
private var requested = false
|
||||
|
||||
private val check = object : Runnable {
|
||||
override fun run() {
|
||||
val handler = handler ?: return
|
||||
if (SessionState.running && SessionState.suspended) {
|
||||
handler.postDelayed(this, SUSPENDED_POLL_MS)
|
||||
return
|
||||
}
|
||||
val result = if (requested) OfflineMode.sync(app()) else OfflineMode.follow(app())
|
||||
if (result != null) requested = false
|
||||
if (result == null && retries < MAX_RETRIES) {
|
||||
retries++
|
||||
handler.postDelayed(this, RETRY_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
val started = HandlerThread("steam-offline").also { it.start() }
|
||||
val handler = Handler(started.looper)
|
||||
thread = started
|
||||
this.handler = handler
|
||||
val registered = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) =
|
||||
changed(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
|
||||
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED))
|
||||
override fun onLost(network: Network) = changed(false)
|
||||
}
|
||||
callback = registered
|
||||
active = this
|
||||
online = AutoComponents.isOnline(app())
|
||||
app().getSystemService(ConnectivityManager::class.java).registerDefaultNetworkCallback(registered, handler)
|
||||
sync()
|
||||
}
|
||||
|
||||
private fun changed(now: Boolean) {
|
||||
val handler = handler ?: return
|
||||
if (now == online) return
|
||||
online = now
|
||||
handler.removeCallbacks(check)
|
||||
retries = 0
|
||||
if (OfflineMode.auto(app())) requested = false
|
||||
handler.postDelayed(check, if (now) ONLINE_DELAY_MS else OFFLINE_DELAY_MS)
|
||||
}
|
||||
|
||||
private fun sync() {
|
||||
handler?.post {
|
||||
val handler = handler ?: return@post
|
||||
handler.removeCallbacks(check)
|
||||
retries = 0
|
||||
requested = true
|
||||
handler.post(check)
|
||||
}
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
if (active === this) active = null
|
||||
val registered = callback
|
||||
callback = null
|
||||
if (registered != null) {
|
||||
try {
|
||||
app().getSystemService(ConnectivityManager::class.java).unregisterNetworkCallback(registered)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
Log.w(TAG, "network callback was already gone", e)
|
||||
}
|
||||
}
|
||||
handler?.removeCallbacksAndMessages(null)
|
||||
handler = null
|
||||
thread?.quitSafely()
|
||||
thread = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SteamOfflineFollow"
|
||||
@Volatile private var active: SteamOfflineFollow? = null
|
||||
const val ONLINE_DELAY_MS = 2_000L
|
||||
const val OFFLINE_DELAY_MS = 10_000L
|
||||
const val RETRY_MS = 15_000L
|
||||
const val MAX_RETRIES = 8
|
||||
const val SUSPENDED_POLL_MS = 1_000L
|
||||
|
||||
fun request() {
|
||||
active?.sync()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,7 +113,7 @@ object CloudSaves {
|
||||
}
|
||||
Store.UBISOFT -> UBISOFT_TEMPLATE
|
||||
Store.EA -> eaRules(context, id) ?: return null
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> ""
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR, Store.STEAM -> ""
|
||||
} ?: return null
|
||||
p.edit()
|
||||
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
|
||||
@@ -181,7 +181,7 @@ object CloudSaves {
|
||||
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
|
||||
Store.EA -> if (sidecar.extra["masterTitleId"].isNullOrEmpty()) null
|
||||
else EaSaveRules.parse(template)?.base()?.let(EaSaveRules::template)?.let { CloudSavePaths.gog(it, pfx, folder) }
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> null
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR, Store.STEAM -> null
|
||||
}
|
||||
return dir to (if (dir == null) "unresolved" else "ok")
|
||||
}
|
||||
@@ -221,7 +221,7 @@ object CloudSaves {
|
||||
if (rules == null || base == null || token == null || uid.isEmpty() || master.isEmpty()) null
|
||||
else EaCloud(token, uid, EaCloud.keys(master, sidecar?.extra?.get("multiplayerId").orEmpty()), base, rules, saveFolder(context, store, id).first)
|
||||
}
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> null
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR, Store.STEAM -> null
|
||||
}
|
||||
|
||||
private fun signedIn(context: Context, store: Store): Boolean = when (store) {
|
||||
|
||||
@@ -16,7 +16,7 @@ internal object LoginFlows {
|
||||
Store.UBISOFT -> ubisoftFlow(browserUserAgent)
|
||||
Store.EA -> eaFlow(browserUserAgent)
|
||||
Store.ROCKSTAR -> rockstarFlow(browserUserAgent)
|
||||
Store.ITCH, Store.XBOX, Store.BATTLENET -> null
|
||||
Store.ITCH, Store.XBOX, Store.BATTLENET, Store.STEAM -> null
|
||||
}
|
||||
|
||||
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
|
||||
|
||||
@@ -10,11 +10,18 @@ enum class Store(val id: String, val label: String, val shortLabel: String) {
|
||||
UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"),
|
||||
AMAZON("amazon", "Amazon Games", "Amazon"),
|
||||
BATTLENET("battlenet", "Battle.net", "Battle.net"),
|
||||
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt");
|
||||
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"),
|
||||
STEAM("steamstore", "Steam", "Steam");
|
||||
|
||||
val folder: String get() = if (this == ITCH) "itch" else shortLabel
|
||||
|
||||
/** The Library tab its games list under: Steam's are the Steam client's own tab. */
|
||||
val librarySource: String get() = if (this == STEAM) com.droiddeck.launcher.frontend.Library.SOURCE_STEAM else id
|
||||
|
||||
companion object {
|
||||
fun byId(id: String?): Store? = entries.firstOrNull { it.id == id }
|
||||
|
||||
/** The stores with a tab of their own; Steam's games list in the Library's Steam tab. */
|
||||
val tabbed: List<Store> get() = entries - STEAM
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ object StoreAccounts {
|
||||
fun signedInAs(context: Context, store: Store): String? {
|
||||
val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null
|
||||
if (store == Store.XBOX) return json.optString("username").takeIf { it.isNotBlank() }
|
||||
if (store == Store.BATTLENET) return json.optString("display_name").takeIf { it.isNotBlank() }
|
||||
if (store == Store.BATTLENET || store == Store.STEAM) return json.optString("display_name").takeIf { it.isNotBlank() }
|
||||
if (json.optString("access_token", "").isEmpty()) return null
|
||||
return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label }
|
||||
}
|
||||
|
||||
@@ -247,7 +247,7 @@ object StoreInstallRoot {
|
||||
fun storeDir(root: File, store: Store): File = File(root, store.folder)
|
||||
|
||||
fun gameFolders(context: Context): List<File> = roots(context).flatMap { root ->
|
||||
Store.entries.flatMap { store ->
|
||||
Store.entries.filter { it != Store.STEAM }.flatMap { store ->
|
||||
storeDir(root, store).listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()
|
||||
}
|
||||
}
|
||||
@@ -267,7 +267,7 @@ object StoreInstallRoot {
|
||||
fun isFinished(folder: File): Boolean = StoreGameSidecar.read(folder)?.isInstalled == true
|
||||
|
||||
fun unfinished(context: Context): List<Unfinished> = roots(context).flatMap { root ->
|
||||
Store.entries.filter { it != Store.BATTLENET }.flatMap { store ->
|
||||
Store.entries.filter { it != Store.BATTLENET && it != Store.STEAM }.flatMap { store ->
|
||||
storeDir(root, store).listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { folder ->
|
||||
val sidecar = StoreGameSidecar.read(folder)
|
||||
when {
|
||||
|
||||
@@ -63,7 +63,7 @@ object StoreSizes {
|
||||
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||
Store.ITCH, Store.GAMEJOLT -> {}
|
||||
Store.EA -> com.droiddeck.launcher.stores.ea.EaPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> {}
|
||||
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR, Store.STEAM -> {}
|
||||
}
|
||||
}
|
||||
}, pool).exceptionally { error ->
|
||||
@@ -142,5 +142,6 @@ object StoreSizes {
|
||||
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> 0L
|
||||
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
|
||||
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item)
|
||||
Store.STEAM -> com.droiddeck.launcher.stores.steam.SteamStore.plannedBytes(context, item)
|
||||
} }
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package com.droiddeck.launcher.stores
|
||||
data class StoreTab(val store: Store, val shown: Boolean)
|
||||
|
||||
fun arrangeStoreTabs(order: List<String>, hidden: Set<String>): List<StoreTab> {
|
||||
val known = Store.entries.associateBy { it.id }
|
||||
val known = Store.tabbed.associateBy { it.id }
|
||||
val listed = order.mapNotNull { known[it] }.distinct()
|
||||
return (listed + Store.entries.filterNot { it in listed }).map { StoreTab(it, it.id !in hidden) }
|
||||
return (listed + Store.tabbed.filterNot { it in listed }).map { StoreTab(it, it.id !in hidden) }
|
||||
}
|
||||
@@ -85,6 +85,7 @@ object StoresState {
|
||||
do {
|
||||
seen = refreshRequests.get()
|
||||
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
|
||||
runCatching { com.droiddeck.launcher.stores.steam.SteamStore.syncAccount(app) }
|
||||
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
|
||||
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
|
||||
@@ -260,6 +261,7 @@ object StoresState {
|
||||
|
||||
fun requestInstall(context: Context, item: CatalogItem) {
|
||||
askForNotifications(context)
|
||||
if (item.store == Store.STEAM) { com.droiddeck.launcher.stores.steam.SteamStore.requestInstall(context, item); return }
|
||||
if (item.store == Store.ITCH && item.extra["uploadId"].isNullOrEmpty()) { itchPicking = item; return }
|
||||
if (item.store == Store.GAMEJOLT && item.extra["buildId"].isNullOrEmpty()) { gameJoltPicking = item; return }
|
||||
if (isUnfinished(item)) { install(context, item); return }
|
||||
@@ -278,6 +280,7 @@ object StoresState {
|
||||
|
||||
fun install(context: Context, item: CatalogItem, root: java.io.File? = null, language: String? = null) {
|
||||
val app = context.applicationContext
|
||||
if (item.store == Store.STEAM) { com.droiddeck.launcher.stores.steam.SteamStore.restore(app, item); return }
|
||||
val targetRoot = root ?: StoreInstallRoot.defaultTarget(app)?.root ?: StoreInstallRoot.installRoot(app)
|
||||
if (item.store == Store.BATTLENET && !com.droiddeck.launcher.stores.battlenet.BattleNetInstall.headless(item)) {
|
||||
backends[item.store]?.install(app, item, targetRoot)
|
||||
|
||||
@@ -159,6 +159,7 @@ object DownloadQueue {
|
||||
}
|
||||
|
||||
fun holdPaused(key: String) = synchronized(lock) { heldPaused.add(key) }
|
||||
fun dropHeld(key: String) = synchronized(lock) { heldPaused.remove(key) }
|
||||
private var running = 0
|
||||
|
||||
fun parallel(context: Context): Int = SessionPrefs.gameStoresParallel(context)
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.droiddeck.launcher.stores.steam
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SteamLibraries
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/** The active Steam client's folders as the app sees them. Reads storage; call off the main thread. */
|
||||
internal object SteamClient {
|
||||
const val X86_64 = "x86_64"
|
||||
|
||||
class Target(
|
||||
val library: SteamLibraryFolders.Library, val engineHost: File, val label: String,
|
||||
val freeBytes: Long, val removable: Boolean, val folder: Boolean,
|
||||
)
|
||||
|
||||
fun activeArch(context: Context): String = SessionPrefs.activeSteamClientArch(context)
|
||||
|
||||
private fun guestHome(arch: String) = if (arch == X86_64) "/root/.droiddeck-x64" else "/root"
|
||||
|
||||
fun guestRoot(arch: String) = "${guestHome(arch)}/.local/share/Steam"
|
||||
|
||||
private fun aliases(arch: String) = listOf(guestRoot(arch), "${guestHome(arch)}/.steam/steam", "${guestHome(arch)}/.steam/root")
|
||||
|
||||
/** [guest] names [library]; the main library also answers to the client's other spellings of its root. */
|
||||
fun sameLibrary(context: Context, library: SteamLibraryFolders.Library, guest: String): Boolean {
|
||||
if (library.guest == guest) return true
|
||||
if (!library.main) return false
|
||||
val arch = activeArch(context)
|
||||
val wanted = SteamLibraryFolders.normalize(guest) ?: return false
|
||||
return (aliases(arch) + guestRoot(arch)).mapNotNull(SteamLibraryFolders::normalize).contains(wanted)
|
||||
}
|
||||
|
||||
fun root(context: Context, arch: String = activeArch(context)): File = SessionPrefs.steamRoot(context, arch)
|
||||
|
||||
fun registry(context: Context, arch: String = activeArch(context)): File =
|
||||
File(LinuxRuntime.rootDir(context), guestHome(arch).removePrefix("/") + "/.steam/registry.vdf")
|
||||
|
||||
fun loginUsers(context: Context, arch: String = activeArch(context)): File = File(root(context, arch), "config/loginusers.vdf")
|
||||
|
||||
fun language(context: Context): String =
|
||||
runCatching { SteamLibraryFolders.language(registry(context).readText()) }.getOrNull() ?: "english"
|
||||
|
||||
fun mounts(context: Context): List<SteamLibraryFolders.Mount> {
|
||||
val out = ArrayList<SteamLibraryFolders.Mount>()
|
||||
GameStorage.effective(context)?.let { card -> SecondaryLibrary.CARD_GUESTS.forEach { out += SteamLibraryFolders.Mount(it, File(card.path)) } }
|
||||
SteamLibraries.list(context).forEach { out += SteamLibraryFolders.Mount(it.guest, it.host) }
|
||||
AddedGames.roots(context).forEach { out += SteamLibraryFolders.Mount(it.guest, it.host) }
|
||||
StoreInstallRoot.externalRoots(context).forEach { (host, guest) -> out += SteamLibraryFolders.Mount(guest, host) }
|
||||
out += SteamLibraryFolders.Mount("/root/Storage", Environment.getExternalStorageDirectory())
|
||||
return out
|
||||
}
|
||||
|
||||
/** Every library the client lists in libraryfolders.vdf that maps to a folder of the app. */
|
||||
fun libraries(context: Context, arch: String = activeArch(context)): List<SteamLibraryFolders.Library> {
|
||||
val root = root(context, arch)
|
||||
val text = runCatching { File(root, "steamapps/libraryfolders.vdf").readText() }.getOrNull().orEmpty()
|
||||
return SteamLibraryFolders.resolve(
|
||||
SteamLibraryFolders.parse(text), guestRoot(arch), aliases(arch), root, mounts(context), LinuxRuntime.rootDir(context),
|
||||
)
|
||||
}
|
||||
|
||||
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
|
||||
|
||||
/** The card and added libraries are written through the raw card view when Android allows it, as the session binds them. */
|
||||
private fun engineView(context: Context): (File) -> File {
|
||||
val bases = listOfNotNull(GameStorage.effective(context)?.let { File(it.path) }) + SteamLibraries.list(context).map { it.host }
|
||||
val seen = HashMap<String, File>()
|
||||
return { host ->
|
||||
val path = host.absolutePath
|
||||
val base = bases.filter { path == it.absolutePath || path.startsWith(it.absolutePath + "/") }.maxByOrNull { it.absolutePath.length }
|
||||
if (base == null) host else {
|
||||
val content = seen.getOrPut(base.absolutePath) { SecondaryLibrary.contentPath(base) }
|
||||
if (content.absolutePath == base.absolutePath) host
|
||||
else path.removePrefix(base.absolutePath).trimStart('/').let { if (it.isEmpty()) content else File(content, it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class EngineLibraries(val libraries: List<Pair<SteamLibraryFolders.Library, File>>) {
|
||||
val json: String get() = JSONArray().apply {
|
||||
for ((library, host) in libraries) put(JSONObject().put("host", host.absolutePath).put("guest", library.guest))
|
||||
}.toString()
|
||||
|
||||
fun hostOf(library: SteamLibraryFolders.Library): File =
|
||||
libraries.firstOrNull { it.first.guest == library.guest }?.second ?: library.host
|
||||
}
|
||||
|
||||
fun engineLibraries(context: Context, arch: String = activeArch(context)): EngineLibraries {
|
||||
val view = engineView(context)
|
||||
return EngineLibraries(libraries(context, arch).filter { it.host.isDirectory }.map { it to view(it.host) })
|
||||
}
|
||||
|
||||
fun targets(context: Context): List<Target> {
|
||||
val arch = activeArch(context)
|
||||
val card = GameStorage.effective(context)?.let { canonical(File(it.path)) }
|
||||
val known = Library.steamLibraries(context, arch).associate { (host, label) ->
|
||||
canonical(host) to if (label == "internal") context.getString(R.string.games_internal) else label
|
||||
}
|
||||
val engine = engineLibraries(context)
|
||||
return engine.libraries.mapNotNull { (library, host) ->
|
||||
if (!library.host.isDirectory || !library.host.canWrite()) return@mapNotNull null
|
||||
val path = canonical(library.host)
|
||||
val onCard = card != null && (path == card || path.startsWith("$card/"))
|
||||
val label = library.label.ifBlank {
|
||||
if (library.main) context.getString(R.string.stores_target_internal) else known[path] ?: File(library.guest).name
|
||||
}
|
||||
Target(library, host, label, StoreInstallRoot.availableBytes(host), removable = onCard, folder = !library.main && !onCard)
|
||||
}
|
||||
}
|
||||
|
||||
/** True while a session that can run the Steam client is up or starting. */
|
||||
fun clientMayRun(): Boolean {
|
||||
val up = SessionState.running || (SessionState.phase != SessionPhase.IDLE && SessionState.phase != SessionPhase.FAILED)
|
||||
return up && SessionState.mode != SessionService.MODE_RUN
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.droiddeck.launcher.stores.steam
|
||||
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.StoresNative
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Blocking calls into the Rust engine; they reach the network, so never on the main thread. */
|
||||
internal object SteamEngine {
|
||||
private const val TAG = "SteamEngine"
|
||||
const val MISSING = "engine_missing"
|
||||
const val MISSING_TEXT = "Steam: the store engine is not available"
|
||||
|
||||
private const val RETRY_MS = 60_000L
|
||||
/** After Steam refuses sign-ins for coming too often, wait well past its limit. */
|
||||
private const val THROTTLED_MS = 30 * 60_000L
|
||||
|
||||
private val lock = Any()
|
||||
@Volatile private var signedIn = false
|
||||
/** The saved login the last sign-in attempt read, so a refusal rejects that login and not one saved since. */
|
||||
@Volatile var attempted: String? = null
|
||||
private set
|
||||
private var failed: JSONObject? = null
|
||||
private var failedAt = 0L
|
||||
|
||||
fun failure(error: String): JSONObject = JSONObject().put("ok", false).put("error", error)
|
||||
|
||||
private fun call(op: String, block: () -> String): JSONObject {
|
||||
if (!StoresNative.ensureLoaded()) return failure(MISSING)
|
||||
val text = try {
|
||||
block()
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
Log.w(TAG, "$op: not in this engine build")
|
||||
return failure(MISSING)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "$op: ${t.javaClass.simpleName}")
|
||||
return failure(t.javaClass.simpleName)
|
||||
}
|
||||
return runCatching { JSONObject(text) }.getOrElse { failure("$op: unreadable answer") }
|
||||
}
|
||||
|
||||
fun signIn(context: Context): JSONObject {
|
||||
synchronized(lock) {
|
||||
if (signedIn) return JSONObject().put("ok", true)
|
||||
failed?.takeIf { SystemClock.elapsedRealtime() - failedAt < waitAfter(it) }?.let { return it }
|
||||
val roots = JSONArray()
|
||||
.put(SessionPrefs.steamRoot(context, "arm64").absolutePath)
|
||||
.put(SessionPrefs.steamRoot(context, SteamClient.X86_64).absolutePath)
|
||||
val registry = SteamClient.registry(context).absolutePath
|
||||
attempted = SteamStore.fingerprint(context)
|
||||
val answer = call("signIn") { SteamNative.nativeSignIn(roots.toString(), registry, "") }
|
||||
signedIn = answer.optBoolean("ok")
|
||||
failed = if (signedIn) null else answer
|
||||
failedAt = SystemClock.elapsedRealtime()
|
||||
if (!signedIn) Log.w(TAG, "sign-in: ${answer.optString("error")}")
|
||||
return answer
|
||||
}
|
||||
}
|
||||
|
||||
private fun waitAfter(failure: JSONObject): Long {
|
||||
val error = failure.optString("error")
|
||||
return if ("RateLimitExceeded" in error || "Throttle" in error) THROTTLED_MS else RETRY_MS
|
||||
}
|
||||
|
||||
fun forget() {
|
||||
synchronized(lock) {
|
||||
failed = null
|
||||
if (!signedIn) return
|
||||
signedIn = false
|
||||
try {
|
||||
SteamNative.nativeSignOut()
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "sign-out: ${t.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun signedCall(context: Context, op: String, block: () -> String): JSONObject {
|
||||
synchronized(lock) {
|
||||
val signIn = signIn(context)
|
||||
if (!signIn.optBoolean("ok")) return signIn
|
||||
val answer = call(op, block)
|
||||
val error = answer.optString("error").lowercase()
|
||||
if (!answer.optBoolean("ok") && listOf("logon", "sign", "session", "connect").any { it in error }) signedIn = false
|
||||
return answer
|
||||
}
|
||||
}
|
||||
|
||||
fun library(context: Context): JSONObject = signedCall(context, "library") { SteamNative.nativeLibrary() }
|
||||
|
||||
fun plan(context: Context, appId: Int, language: String): JSONObject =
|
||||
signedCall(context, "plan") { SteamNative.nativePlan(appId, language) }
|
||||
|
||||
fun uninstall(appId: Int, steamRoot: String, host: String, guest: String, roots: String): JSONObject {
|
||||
synchronized(lock) {
|
||||
return call("uninstall") { SteamNative.nativeUninstall(appId, steamRoot, host, guest, roots) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.droiddeck.launcher.stores.steam
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.download.StoreDownloadTier
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/** Called by the engine on its own threads. */
|
||||
interface SteamInstallListener {
|
||||
fun onProgress(doneBytes: Long, totalBytes: Long, phase: String?)
|
||||
fun onComplete(ok: Boolean, result: String?)
|
||||
}
|
||||
|
||||
internal class SteamInstallJob(
|
||||
private val app: Context,
|
||||
private val appId: Int,
|
||||
private val libraryGuest: String,
|
||||
) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
private val started = AtomicBoolean(false)
|
||||
@Volatile private var discard = false
|
||||
@Volatile private var installDir: String? = null
|
||||
@Volatile private var createdDir = false
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
started.set(true)
|
||||
try {
|
||||
return install(handle)
|
||||
} finally {
|
||||
if (discard) SteamStore.discardPartial(app, appId, libraryGuest, installDir, createdDir)
|
||||
}
|
||||
}
|
||||
|
||||
private fun install(handle: DownloadQueue.JobHandle): String? {
|
||||
handle.stage(DownloadStage.MANIFEST)
|
||||
if (SteamClient.clientMayRun()) throw IllegalStateException(app.getString(R.string.steam_store_close_steam))
|
||||
val engine = SteamClient.engineLibraries(app)
|
||||
val target = engine.libraries.firstOrNull { SteamClient.sameLibrary(app, it.first, libraryGuest) }
|
||||
?: throw IllegalStateException(app.getString(R.string.game_sync_err_steam_library))
|
||||
val signIn = SteamEngine.signIn(app)
|
||||
if (!signIn.optBoolean("ok")) {
|
||||
SteamStore.signInFailed(app, signIn.optString("error"))
|
||||
throw IllegalStateException(SteamStore.errorText(app, signIn))
|
||||
}
|
||||
val language = SteamClient.language(app)
|
||||
val (plan, planned) = SteamStore.plan(app, appId, language)
|
||||
if (plan == null) throw IllegalStateException(SteamStore.errorText(app, planned))
|
||||
installDir = plan.installDir
|
||||
createdDir = SteamStore.claimFolder(app, appId, libraryGuest, File(target.second, "steamapps/common/${plan.installDir}"))
|
||||
if (plan.installBytes > 0) handle.diskSize(plan.installBytes)
|
||||
if (cancelled.get()) return null
|
||||
|
||||
val tier = StoreDownloadTier.current(app)
|
||||
val journal = File(app.filesDir, "${SteamStore.JOURNAL}/$appId").apply { mkdirs() }
|
||||
handle.log("steam: $appId tier=${tier.id} window=${tier.networkWindow} process_workers=${tier.processWorkers}")
|
||||
val done = CountDownLatch(1)
|
||||
val succeeded = AtomicBoolean(false)
|
||||
val answer = AtomicReference("")
|
||||
val listener = object : SteamInstallListener {
|
||||
private var stage: DownloadStage? = null
|
||||
private var shown = -1L
|
||||
|
||||
override fun onProgress(doneBytes: Long, totalBytes: Long, phase: String?) {
|
||||
synchronized(this) {
|
||||
val now = SteamLibraryFolders.stageOf(phase.orEmpty())
|
||||
if (now != stage) {
|
||||
stage = now
|
||||
shown = -1L
|
||||
}
|
||||
if (doneBytes < shown) return
|
||||
shown = doneBytes
|
||||
if (now == DownloadStage.DOWNLOAD) handle.progress(doneBytes, totalBytes)
|
||||
else {
|
||||
handle.stage(now)
|
||||
if (totalBytes > 0) handle.stageProgress(doneBytes, totalBytes, bytes = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onComplete(ok: Boolean, result: String?) {
|
||||
answer.set(result.orEmpty())
|
||||
succeeded.set(ok)
|
||||
done.countDown()
|
||||
}
|
||||
}
|
||||
val native = try {
|
||||
SteamNative.nativeStart(
|
||||
appId, language, SteamClient.root(app).absolutePath, target.second.absolutePath, target.first.guest, engine.json,
|
||||
journal.absolutePath, "", tier.networkWindow.coerceIn(1, 128), tier.processWorkers, listener,
|
||||
)
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
throw IllegalStateException(SteamEngine.MISSING_TEXT)
|
||||
}
|
||||
if (native == 0L && done.count > 0L) throw IllegalStateException(SteamStore.errorText(app, parse(answer.get())))
|
||||
if (native != 0L) {
|
||||
try {
|
||||
var forwarded = false
|
||||
while (true) {
|
||||
val finished = try {
|
||||
done.await(CANCEL_POLL_MS, TimeUnit.MILLISECONDS)
|
||||
} catch (e: InterruptedException) {
|
||||
cancelled.set(true)
|
||||
false
|
||||
}
|
||||
if (finished) break
|
||||
if (!forwarded && cancelled.get()) {
|
||||
runCatching { SteamNative.nativeCancel(native) }
|
||||
forwarded = true
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
runCatching { SteamNative.nativeRelease(native) }
|
||||
}
|
||||
}
|
||||
val result = parse(answer.get())
|
||||
if (succeeded.get() && result.optBoolean("ok", true)) {
|
||||
SteamStore.forgetJournal(app, appId, libraryGuest, target.first.guest)
|
||||
return File(target.first.host, "steamapps/common/${plan.installDir}").path
|
||||
}
|
||||
if (cancelled.get() || result.optString("error") == "cancelled") return null
|
||||
throw IllegalStateException(SteamStore.errorText(app, result))
|
||||
}
|
||||
|
||||
private fun parse(text: String): JSONObject =
|
||||
runCatching { JSONObject(text) }.getOrElse { SteamEngine.failure(text.ifBlank { "install failed" }) }
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (!deleteFiles) return
|
||||
discard = true
|
||||
if (!started.get()) SteamStore.discardPartial(app, appId, libraryGuest, null, SteamStore.createdFolder(app, appId, libraryGuest))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val CANCEL_POLL_MS = 250L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package com.droiddeck.launcher.stores.steam
|
||||
|
||||
import com.droiddeck.launcher.storage.SteamStorage
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import java.io.File
|
||||
|
||||
internal object SteamLibraryFolders {
|
||||
data class Folder(val path: String, val label: String)
|
||||
|
||||
class Mount(guest: String, val host: File) {
|
||||
val guest: String = guest.trimEnd('/')
|
||||
}
|
||||
|
||||
data class Library(val guest: String, val host: File, val label: String, val main: Boolean)
|
||||
|
||||
data class Installed(val appId: Int, val name: String, val installDir: String?, val library: Library, val sizeOnDisk: Long)
|
||||
|
||||
/** Guest folders that exist only as binds of the session; without their bind they are empty mount points in the rootfs. */
|
||||
val BIND_ONLY = listOf("/mnt", "/media", "/storage", "/sdcard", "/root/Storage", "/root/ROMs", "/root/Games")
|
||||
|
||||
private val TOKEN = Regex("\"((?:\\\\.|[^\"\\\\])*)\"|[{}]|//[^\n]*")
|
||||
private val ACF = Regex("appmanifest_\\d+\\.acf")
|
||||
private val SIZE_ON_DISK = Regex("^\\s*\"SizeOnDisk\"\\s*\"(\\d+)\"", setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE))
|
||||
|
||||
private fun walk(text: String, pair: (blocks: List<String>, key: String, value: String) -> Unit, closed: (blocks: List<String>) -> Unit = {}) {
|
||||
val blocks = ArrayList<String>()
|
||||
var key: String? = null
|
||||
for (m in TOKEN.findAll(text)) {
|
||||
val token = m.value
|
||||
when {
|
||||
token.startsWith("//") -> {}
|
||||
token == "{" -> { blocks.add(key.orEmpty()); key = null }
|
||||
token == "}" -> { if (blocks.isNotEmpty()) { closed(blocks); blocks.removeAt(blocks.lastIndex) }; key = null }
|
||||
key == null -> key = unescape(m.groupValues[1])
|
||||
else -> { pair(blocks, key, unescape(m.groupValues[1])); key = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun unescape(s: String): String {
|
||||
if ('\\' !in s) return s
|
||||
val out = StringBuilder(s.length)
|
||||
var i = 0
|
||||
while (i < s.length) {
|
||||
if (s[i] == '\\' && i + 1 < s.length) { out.append(s[i + 1]); i += 2 } else { out.append(s[i]); i++ }
|
||||
}
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
private fun inRoot(blocks: List<String>) = blocks.firstOrNull()?.equals("libraryfolders", ignoreCase = true) == true
|
||||
|
||||
fun parse(text: String): List<Folder> {
|
||||
val out = ArrayList<Folder>()
|
||||
var path: String? = null
|
||||
var label = ""
|
||||
walk(text, pair = { blocks, key, value ->
|
||||
if (!inRoot(blocks)) return@walk
|
||||
if (blocks.size == 1 && key.isNotEmpty() && key.all(Char::isDigit)) out += Folder(value, "")
|
||||
if (blocks.size == 2) when (key.lowercase()) {
|
||||
"path" -> path = value
|
||||
"label" -> label = value
|
||||
}
|
||||
}, closed = { blocks ->
|
||||
if (blocks.size == 2 && inRoot(blocks)) path?.let { out += Folder(it, label) }
|
||||
if (blocks.size == 2) { path = null; label = "" }
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
fun normalize(path: String): String? {
|
||||
val p = path.trim().replace(Regex("/+"), "/").trimEnd('/')
|
||||
if (!p.startsWith("/") || p.split('/').any { it == ".." || it == "." }) return null
|
||||
return p
|
||||
}
|
||||
|
||||
private fun under(path: String, prefix: String) = path == prefix || path.startsWith("$prefix/")
|
||||
|
||||
fun hostFor(guest: String, mounts: List<Mount>, rootfs: File): File? {
|
||||
val path = normalize(guest) ?: return null
|
||||
mounts.filter { it.guest.isNotEmpty() && under(path, it.guest) }.maxByOrNull { it.guest.length }?.let { m ->
|
||||
val rest = path.removePrefix(m.guest).trimStart('/')
|
||||
return if (rest.isEmpty()) m.host else File(m.host, rest)
|
||||
}
|
||||
if (BIND_ONLY.any { under(path, it) } || !under(path, "/root")) return null
|
||||
return File(rootfs, path.removePrefix("/"))
|
||||
}
|
||||
|
||||
fun resolve(folders: List<Folder>, mainGuest: String, aliases: Collection<String>, mainHost: File, mounts: List<Mount>, rootfs: File): List<Library> {
|
||||
val mains = (aliases + mainGuest).mapNotNull(::normalize).toSet()
|
||||
val listed = if (folders.any { normalize(it.path) in mains }) folders else listOf(Folder(mainGuest, "")) + folders
|
||||
val out = ArrayList<Library>()
|
||||
// The main library first, so an entry reaching the same folder under another path cannot take its place.
|
||||
for (f in listed.sortedByDescending { normalize(it.path) in mains }) {
|
||||
val guest = normalize(f.path) ?: continue
|
||||
val main = guest in mains
|
||||
val host = if (main) mainHost else hostFor(guest, mounts, rootfs) ?: continue
|
||||
if (out.any { it.host.path == host.path || (main && it.main) }) continue
|
||||
out += Library(guest, host, f.label.trim(), main)
|
||||
}
|
||||
return out.sortedByDescending { it.main }
|
||||
}
|
||||
|
||||
fun installed(libraries: List<Library>, read: (File) -> String? = { runCatching { it.readText() }.getOrNull() }): Map<Int, Installed> {
|
||||
val out = LinkedHashMap<Int, Installed>()
|
||||
for (library in libraries) {
|
||||
val apps = File(library.host, "steamapps")
|
||||
val names = apps.list() ?: continue
|
||||
for (name in names.sorted()) {
|
||||
if (!ACF.matches(name)) continue
|
||||
val file = File(apps, name)
|
||||
val text = read(file) ?: continue
|
||||
val manifest = SteamStorage.parseManifest(file, text) ?: continue
|
||||
if (!manifest.installed || SteamStorage.isTool(manifest) || manifest.appId in out) continue
|
||||
val size = SIZE_ON_DISK.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
|
||||
out[manifest.appId] = Installed(manifest.appId, manifest.name, manifest.installDir, library, size)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
data class SavedAccount(val id: String, val name: String)
|
||||
|
||||
fun savedAccount(loginUsers: String): String? = savedLogin(loginUsers)?.name
|
||||
|
||||
/**
|
||||
* The account the client signs in with by itself, chosen as the engine does: `AutoLoginUser`, else the most recent, else the newest;
|
||||
* none when that account opted out of Remember me. [SavedAccount.id] is its SteamID64.
|
||||
*/
|
||||
fun savedLogin(loginUsers: String, registry: String = ""): SavedAccount? {
|
||||
val users = LinkedHashMap<String, HashMap<String, String>>()
|
||||
walk(loginUsers, pair = { blocks, key, value ->
|
||||
if (blocks.size == 2 && blocks[0].equals("users", ignoreCase = true)) users.getOrPut(blocks[1]) { HashMap() }[key.lowercase()] = value
|
||||
})
|
||||
val accounts = users.entries.filter { it.key.all(Char::isDigit) && !it.value["accountname"].isNullOrBlank() }
|
||||
val auto = autoLoginUser(registry)
|
||||
val (id, user) = auto?.let { name -> accounts.firstOrNull { it.value["accountname"].equals(name, ignoreCase = true) } }
|
||||
?: accounts.firstOrNull { it.value["mostrecent"] == "1" }
|
||||
?: accounts.maxByOrNull { it.value["timestamp"]?.toLongOrNull() ?: 0L }
|
||||
?: return null
|
||||
if (user["rememberpassword"] == "0") return null
|
||||
val name = user["personaname"]?.takeIf { it.isNotBlank() } ?: user["accountname"]?.takeIf { it.isNotBlank() } ?: return null
|
||||
return SavedAccount(id, name)
|
||||
}
|
||||
|
||||
fun autoLoginUser(registry: String): String? {
|
||||
var found: String? = null
|
||||
walk(registry, pair = { blocks, key, value ->
|
||||
if (found == null && key.equals("AutoLoginUser", ignoreCase = true) && blocks.lastOrNull().equals("Steam", ignoreCase = true) && value.isNotBlank()) found = value
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
fun language(registry: String): String? {
|
||||
var found: String? = null
|
||||
walk(registry, pair = { blocks, key, value ->
|
||||
if (found == null && key.equals("language", ignoreCase = true) && blocks.lastOrNull().equals("Steam", ignoreCase = true) && value.isNotBlank()) found = value
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
fun stageOf(phase: String): DownloadStage {
|
||||
val p = phase.lowercase()
|
||||
return when {
|
||||
"verif" in p || "validat" in p -> DownloadStage.VERIFY
|
||||
listOf("install", "regist", "final", "commit", "acf", "apply").any { it in p } -> DownloadStage.INSTALL
|
||||
listOf("manifest", "plan", "prepar", "check", "scan", "clean", "alloc", "connect", "logon", "login", "sign").any { it in p } -> DownloadStage.MANIFEST
|
||||
else -> DownloadStage.DOWNLOAD
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.droiddeck.launcher.stores.steam
|
||||
|
||||
object SteamNative {
|
||||
@JvmStatic external fun nativeSignIn(steamRootsJson: String, registryVdfPath: String, caBundlePath: String): String
|
||||
@JvmStatic external fun nativeSignOut()
|
||||
@JvmStatic external fun nativeLibrary(): String
|
||||
@JvmStatic external fun nativePlan(appId: Int, language: String): String
|
||||
@JvmStatic external fun nativeStart(appId: Int, language: String, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String, journalDir: String, caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: Any): Long
|
||||
@JvmStatic external fun nativeCancel(handle: Long)
|
||||
@JvmStatic external fun nativeRelease(handle: Long)
|
||||
@JvmStatic external fun nativeUninstall(appId: Int, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String): String
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
package com.droiddeck.launcher.stores.steam
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.storage.SteamStorage
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreAccounts
|
||||
import com.droiddeck.launcher.stores.StoreBackend
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.StoreSizes
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import com.droiddeck.launcher.stores.download.SavedQueue
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/** Games land in the active client's own libraries, registered as the client does, and only while no session can run the client. */
|
||||
internal object SteamStore {
|
||||
private const val TAG = "SteamStore"
|
||||
private const val PREFS = "steam-store"
|
||||
internal const val JOURNAL = "steam-store/journal"
|
||||
private const val CDN = "https://cdn.cloudflare.steamstatic.com/steam/apps/"
|
||||
private const val LIBRARY = "library"
|
||||
private const val LIBRARY_LABEL = "libraryLabel"
|
||||
private val SIGNED_OUT = setOf("no_saved_login", "remember_me_off", "decrypt_failed")
|
||||
private val REFUSED = Regex("logon_failed: eresult=(-?\\d+).*")
|
||||
/** InvalidPassword, AccessDenied, AccountNotFound, Revoked, Expired, AccountLogonDenied. */
|
||||
private val REFUSALS = setOf(5, 15, 18, 26, 27, 63)
|
||||
|
||||
var picking by mutableStateOf<CatalogItem?>(null)
|
||||
|
||||
class Plan(val installDir: String, val downloadBytes: Long, val installBytes: Long, val buildId: String, val linuxBuild: Boolean) {
|
||||
companion object {
|
||||
fun of(json: JSONObject): Plan? {
|
||||
if (!json.optBoolean("ok")) return null
|
||||
val dir = json.optString("installDir").takeIf { SteamStore.validDir(it) } ?: return null
|
||||
return Plan(dir, json.optLong("downloadBytes"), json.optLong("installBytes"), json.optString("buildId"), json.optBoolean("linuxBuild"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal const val LINUX_BUILD = "linux_build"
|
||||
|
||||
/** Each plan with the language it was made for. */
|
||||
private val plans = ConcurrentHashMap<Int, Pair<String, Plan>>()
|
||||
private val work = Executors.newSingleThreadExecutor { r -> Thread(r, "steam-store") }
|
||||
@Volatile private var rejectedThisRun: String? = null
|
||||
|
||||
fun key(appId: Int): String = "${Store.STEAM.id}:$appId"
|
||||
|
||||
private fun validDir(dir: String) = dir.isNotBlank() && dir != "." && dir != ".." && '/' !in dir && '\\' !in dir
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
|
||||
private fun toast(context: Context, @StringRes text: Int) {
|
||||
val app = context.applicationContext
|
||||
StoresState.post { Toast.makeText(app, text, Toast.LENGTH_LONG).show() }
|
||||
}
|
||||
|
||||
/** Steam refusing the saved login; a connection failure or a throttled logon leaves the account as it is. */
|
||||
internal fun isSignInError(error: String) =
|
||||
error in SIGNED_OUT || REFUSED.matchEntire(error)?.groupValues?.get(1)?.toIntOrNull() in REFUSALS
|
||||
|
||||
internal fun errorText(context: Context, answer: JSONObject): String {
|
||||
val error = answer.optString("error")
|
||||
return when {
|
||||
error == SteamEngine.MISSING -> SteamEngine.MISSING_TEXT
|
||||
error == LINUX_BUILD -> context.getString(R.string.steam_store_linux_build)
|
||||
isSignInError(error) -> context.getString(R.string.stores_login_title, Store.STEAM.label)
|
||||
error.isBlank() -> "Steam: install failed"
|
||||
else -> error
|
||||
}
|
||||
}
|
||||
|
||||
internal fun fingerprint(context: Context): String {
|
||||
val users = SteamClient.loginUsers(context)
|
||||
val registry = SteamClient.registry(context)
|
||||
return "${SteamClient.activeArch(context)}:${users.lastModified()}:${users.length()}:${registry.lastModified()}:${registry.length()}"
|
||||
}
|
||||
|
||||
private fun savedAccount(context: Context): SteamLibraryFolders.SavedAccount? {
|
||||
val print = fingerprint(context)
|
||||
if (print == rejectedThisRun || print == prefs(context).getString("rejected", null)) return null
|
||||
val registry = runCatching { SteamClient.registry(context).readText() }.getOrDefault("")
|
||||
return runCatching { SteamLibraryFolders.savedLogin(SteamClient.loginUsers(context).readText(), registry) }.getOrNull()
|
||||
}
|
||||
|
||||
/** Mirrors the client's saved sign-in into the store account; reads storage. A new name for the same account only relabels it. */
|
||||
fun syncAccount(context: Context): Boolean {
|
||||
val saved = savedAccount(context)
|
||||
val stored = StoreAccounts.read(context, Store.STEAM)
|
||||
val storedId = stored?.optString("steam_id").orEmpty()
|
||||
if (saved != null && saved.id == storedId) {
|
||||
if (saved.name != stored?.optString("display_name")) {
|
||||
StoreAccounts.write(context, Store.STEAM, JSONObject().put("display_name", saved.name).put("steam_id", saved.id))
|
||||
}
|
||||
return false
|
||||
}
|
||||
if (saved == null && stored == null) return false
|
||||
if (saved == null) StoreAccounts.clear(context, Store.STEAM)
|
||||
else StoreAccounts.write(context, Store.STEAM, JSONObject().put("display_name", saved.name).put("steam_id", saved.id))
|
||||
plans.clear()
|
||||
SteamEngine.forget()
|
||||
StoresState.post {
|
||||
StoresState.library.remove(Store.STEAM)
|
||||
StoresState.problems.remove(Store.STEAM)
|
||||
}
|
||||
Log.i(TAG, if (saved == null) "no saved Steam sign-in" else "Steam sign-in found")
|
||||
return true
|
||||
}
|
||||
|
||||
internal fun signInFailed(context: Context, error: String) {
|
||||
if (!isSignInError(error)) return
|
||||
val print = fingerprint(context)
|
||||
if (SteamEngine.attempted?.let { it != print } == true) return
|
||||
rejectedThisRun = print
|
||||
if (error in SIGNED_OUT) prefs(context).edit().putString("rejected", print).apply()
|
||||
StoreAccounts.clear(context, Store.STEAM)
|
||||
StoresState.logLine("Steam: the saved sign-in was not accepted ($error)")
|
||||
StoresState.post {
|
||||
StoresState.accounts.remove(Store.STEAM)
|
||||
StoresState.library.remove(Store.STEAM)
|
||||
}
|
||||
}
|
||||
|
||||
fun downloading(): Boolean = StoresState.latestDownloads.any {
|
||||
it.store == Store.STEAM && (it.state == DownloadState.RUNNING || it.state == DownloadState.QUEUED)
|
||||
}
|
||||
|
||||
/** A Steam store download holds every session that could start the Steam client. */
|
||||
fun blocksSession(intent: Intent?): Boolean {
|
||||
val mode = intent?.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||
return mode != SessionService.MODE_RUN && (downloading() || StoresState.uninstalling.keys.any { it.startsWith("${Store.STEAM.id}:") })
|
||||
}
|
||||
|
||||
internal fun syncLibrary(context: Context, force: Boolean) {
|
||||
val app = context.applicationContext
|
||||
if (force) plans.clear()
|
||||
work.execute {
|
||||
val answer = SteamEngine.library(app)
|
||||
if (!answer.optBoolean("ok")) {
|
||||
val error = answer.optString("error")
|
||||
if (isSignInError(error)) signInFailed(app, error)
|
||||
else StoresState.post {
|
||||
StoresState.problems[Store.STEAM] = errorText(app, answer)
|
||||
StoresState.library[Store.STEAM] = emptyList()
|
||||
}
|
||||
return@execute
|
||||
}
|
||||
val art = runCatching { Library.steamLibraryArt(app).toMap() }.getOrDefault(emptyMap())
|
||||
val items = items(answer.optJSONArray("games"), art)
|
||||
StoresState.logLine("Steam: library has ${items.size} games")
|
||||
StoresState.post {
|
||||
StoresState.problems.remove(Store.STEAM)
|
||||
StoresState.library[Store.STEAM] = items
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun items(games: JSONArray?, art: Map<Int, File>): List<CatalogItem> {
|
||||
val out = ArrayList<CatalogItem>()
|
||||
for (i in 0 until (games?.length() ?: 0)) {
|
||||
val game = games?.optJSONObject(i) ?: continue
|
||||
val id = game.optInt("appId").takeIf { it > 0 } ?: continue
|
||||
val type = game.optString("type").lowercase()
|
||||
if (type.isNotEmpty() && type != "game") continue
|
||||
val name = game.optString("name").takeIf { it.isNotBlank() } ?: continue
|
||||
out += CatalogItem(
|
||||
Store.STEAM, id.toString(), name,
|
||||
imageUrl = "$CDN$id/header.jpg",
|
||||
tallImageUrl = art[id]?.let { Uri.fromFile(it).toString() } ?: "$CDN$id/library_600x900.jpg",
|
||||
isFree = game.optBoolean("free"),
|
||||
storeUrl = "https://store.steampowered.com/app/$id/",
|
||||
owned = true,
|
||||
)
|
||||
}
|
||||
return out.distinctBy { it.id }.sortedBy { it.title.lowercase() }
|
||||
}
|
||||
|
||||
/** Reaches the network; call off the main thread. */
|
||||
internal fun plan(context: Context, appId: Int, language: String = SteamClient.language(context)): Pair<Plan?, JSONObject> {
|
||||
val plan = plans[appId]?.takeIf { it.first == language }?.second ?: run {
|
||||
val answer = SteamEngine.plan(context, appId, language)
|
||||
val error = answer.optString("error")
|
||||
if (isSignInError(error)) signInFailed(context, error)
|
||||
Plan.of(answer)?.also { plans[appId] = language to it } ?: return null to answer
|
||||
}
|
||||
if (plan.linuxBuild && !protonMapped(context, appId)) return null to SteamEngine.failure(LINUX_BUILD)
|
||||
return plan to JSONObject().put("ok", true)
|
||||
}
|
||||
|
||||
/** The engine installs the Windows depots; a game with a Linux build gets those from the client only when it is mapped to a Proton. */
|
||||
private fun protonMapped(context: Context, appId: Int): Boolean {
|
||||
val config = runCatching { File(SteamClient.root(context), "config/config.vdf").readText() }.getOrNull() ?: return false
|
||||
return SteamStorage.compatMappings(config)[appId.toString()]?.contains("proton", ignoreCase = true) == true
|
||||
}
|
||||
|
||||
internal fun plannedBytes(context: Context, item: CatalogItem): Long =
|
||||
item.id.toIntOrNull()?.let { plan(context, it).first?.installBytes } ?: 0L
|
||||
|
||||
fun requestInstall(context: Context, item: CatalogItem) {
|
||||
if (SteamClient.clientMayRun()) {
|
||||
toast(context, R.string.steam_store_close_steam)
|
||||
return
|
||||
}
|
||||
picking = item
|
||||
}
|
||||
|
||||
fun install(context: Context, item: CatalogItem, target: SteamClient.Target) {
|
||||
val app = context.applicationContext
|
||||
val appId = item.id.toIntOrNull() ?: return
|
||||
if (SteamClient.clientMayRun()) {
|
||||
toast(app, R.string.steam_store_close_steam)
|
||||
return
|
||||
}
|
||||
val plan = plans[appId]?.second
|
||||
val needed = plan?.installBytes ?: 0L
|
||||
val tagged = item.copy(extra = item.extra + mapOf(LIBRARY to target.library.guest, LIBRARY_LABEL to target.label))
|
||||
val entry = DownloadEntry(
|
||||
Store.STEAM, item.id, item.title, cover = item.imageUrl,
|
||||
bytesTotal = plan?.downloadBytes ?: 0L, location = target.label,
|
||||
)
|
||||
SavedQueue.remember(app, tagged, target.library.host)
|
||||
if (StoreInstallRoot.insufficientSpace(needed, target.freeBytes)) {
|
||||
val error = app.getString(R.string.stores_storage_insufficient, formatBytes(needed), formatBytes(target.freeBytes))
|
||||
DownloadQueue.recordFailed(app, entry, error) { requestInstall(app, item) }
|
||||
return
|
||||
}
|
||||
DownloadQueue.enqueue(app, entry) { SteamInstallJob(app, appId, target.library.guest) }
|
||||
}
|
||||
|
||||
internal fun restore(context: Context, item: CatalogItem) {
|
||||
val app = context.applicationContext
|
||||
val appId = item.id.toIntOrNull() ?: return
|
||||
val guest = item.extra[LIBRARY] ?: return
|
||||
work.execute {
|
||||
// Either client may have finished the install from where this download was paused.
|
||||
if (installedByAClient(app, appId)) {
|
||||
DownloadQueue.dropHeld(key(appId))
|
||||
StoresState.logLine("Steam: \"${item.title}\" was finished by Steam; its saved download is dropped")
|
||||
return@execute
|
||||
}
|
||||
StoresState.post {
|
||||
SavedQueue.remember(app, item, null)
|
||||
val entry = DownloadEntry(Store.STEAM, item.id, item.title, cover = item.imageUrl, location = item.extra[LIBRARY_LABEL].orEmpty())
|
||||
DownloadQueue.enqueue(app, entry) { SteamInstallJob(app, appId, guest) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun installedByAClient(context: Context, appId: Int): Boolean = listOf("arm64", SteamClient.X86_64).any { arch ->
|
||||
runCatching { appId in SteamLibraryFolders.installed(SteamClient.libraries(context, arch)) }.getOrDefault(false)
|
||||
}
|
||||
|
||||
/** Removes a game like the client does; [fallback] deletes it when the engine cannot (no engine, or a library it does not map). */
|
||||
fun uninstall(context: Context, appId: Int, manifest: File?, fallback: () -> Boolean, onDone: () -> Unit = {}) {
|
||||
val app = context.applicationContext
|
||||
if (SteamClient.clientMayRun()) {
|
||||
toast(app, R.string.steam_store_close_steam)
|
||||
return
|
||||
}
|
||||
val key = key(appId)
|
||||
if (key in StoresState.uninstalling) return
|
||||
StoresState.uninstalling[key] = 0f
|
||||
Thread({
|
||||
if (!DownloadQueue.holdForRemovalWhenFree(key)) {
|
||||
StoresState.logLine("Steam: kept $appId, its download is still running")
|
||||
StoresState.post { StoresState.uninstalling.remove(key); onDone() }
|
||||
return@Thread
|
||||
}
|
||||
val answer = try { runCatching {
|
||||
val apps = manifest?.parentFile?.let(::canonical)
|
||||
// The game may sit in the other client's library; that client's files are the ones to update.
|
||||
val active = SteamClient.activeArch(app)
|
||||
val found = listOf(active, if (active == SteamClient.X86_64) "arm64" else SteamClient.X86_64).firstNotNullOfOrNull { arch ->
|
||||
val libraries = SteamClient.libraries(app, arch)
|
||||
val chosen = if (apps == null) libraries else libraries.filter { canonical(File(it.host, "steamapps")) == apps }
|
||||
SteamLibraryFolders.installed(chosen)[appId]?.let { arch to it }
|
||||
}
|
||||
val answer = if (found == null) SteamEngine.failure(SteamEngine.MISSING) else {
|
||||
val (arch, game) = found
|
||||
val engine = SteamClient.engineLibraries(app, arch)
|
||||
SteamEngine.uninstall(appId, SteamClient.root(app, arch).absolutePath, engine.hostOf(game.library).absolutePath, game.library.guest, engine.json)
|
||||
}
|
||||
when {
|
||||
answer.optString("error") != SteamEngine.MISSING -> answer
|
||||
fallback() -> JSONObject().put("ok", true)
|
||||
else -> SteamEngine.failure("remove_failed")
|
||||
}
|
||||
}.getOrElse { SteamEngine.failure(it.javaClass.simpleName) } } finally { DownloadQueue.releaseRemoval(key) }
|
||||
val ok = answer.optBoolean("ok")
|
||||
StoresState.logLine(if (ok) "Steam: uninstalled $appId" else "Steam: uninstall of $appId failed: ${answer.optString("error")}")
|
||||
StoresState.post {
|
||||
StoresState.uninstalling.remove(key)
|
||||
if (ok) StoreSizes.onDisk.remove(key)
|
||||
else Toast.makeText(app, errorText(app, answer), Toast.LENGTH_LONG).show()
|
||||
onDone()
|
||||
}
|
||||
}, "steam-uninstall").start()
|
||||
}
|
||||
|
||||
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
|
||||
|
||||
/** The engine keys an app's resume journal by library as `<journal>/<appId>/<appId>/<crc32 of the guest path>`. */
|
||||
private fun libraryKey(guest: String): String =
|
||||
"%08x".format(java.util.zip.CRC32().apply { update(guest.trimEnd('/').toByteArray()) }.value)
|
||||
|
||||
private fun createdMarker(context: Context, appId: Int, guest: String) =
|
||||
File(context.filesDir, "$JOURNAL/$appId/created-${libraryKey(guest)}")
|
||||
|
||||
/** Drops the resume state of one app in one library; other libraries' downloads of the app keep theirs. */
|
||||
internal fun forgetJournal(context: Context, appId: Int, guest: String, engineGuest: String? = null) {
|
||||
val app = File(context.filesDir, "$JOURNAL/$appId")
|
||||
val spelled = engineGuest ?: runCatching {
|
||||
SteamClient.engineLibraries(context).libraries.firstOrNull { SteamClient.sameLibrary(context, it.first, guest) }?.first?.guest
|
||||
}.getOrNull() ?: guest
|
||||
File(app, "$appId/${libraryKey(spelled)}").deleteRecursively()
|
||||
createdMarker(context, appId, guest).delete()
|
||||
File(app, "$appId").delete()
|
||||
app.delete()
|
||||
}
|
||||
|
||||
/** Whether this install made the game folder in that library: decided by its first attempt and kept for every resume. */
|
||||
internal fun claimFolder(context: Context, appId: Int, guest: String, folder: File): Boolean {
|
||||
val marker = createdMarker(context, appId, guest)
|
||||
if (marker.isFile) return true
|
||||
if (folder.exists()) return false
|
||||
marker.parentFile?.mkdirs()
|
||||
return runCatching { marker.writeText(folder.name); true }.getOrDefault(false)
|
||||
}
|
||||
|
||||
internal fun createdFolder(context: Context, appId: Int, guest: String): Boolean = createdMarker(context, appId, guest).isFile
|
||||
|
||||
/**
|
||||
* Removes what a cancelled download left; a finished install stays. The game folder goes only when this download made it
|
||||
* ([createdDir]) and no other installed game uses it.
|
||||
*/
|
||||
internal fun discardPartial(context: Context, appId: Int, guest: String, installDir: String?, createdDir: Boolean) {
|
||||
// An unmounted library keeps its journal and ownership record, so a later cancel can still clean it up.
|
||||
val library = runCatching {
|
||||
SteamClient.engineLibraries(context).libraries.firstOrNull { SteamClient.sameLibrary(context, it.first, guest) }?.second
|
||||
}.getOrNull() ?: return
|
||||
val apps = File(library, "steamapps")
|
||||
val acf = File(apps, "appmanifest_$appId.acf")
|
||||
val manifest = acf.takeIf { it.isFile }?.let { f -> runCatching { SteamStorage.parseManifest(f, f.readText()) }.getOrNull() }
|
||||
if (manifest?.installed == true) { forgetJournal(context, appId, guest); return }
|
||||
val claimed = runCatching { createdMarker(context, appId, guest).readText() }.getOrNull()?.ifEmpty { null }
|
||||
val dir = (installDir ?: claimed ?: manifest?.installDir ?: plans[appId]?.second?.installDir)?.takeIf { validDir(it) }
|
||||
val shared = dir != null && apps.listFiles { f -> f.name.startsWith("appmanifest_") && f.name != acf.name }.orEmpty().any { f ->
|
||||
runCatching { SteamStorage.parseManifest(f, f.readText()) }.getOrNull()?.installDir == dir
|
||||
}
|
||||
if (dir != null && createdDir && !shared) StoreInstalls.deleteTree(File(apps, "common/$dir"))
|
||||
StoreInstalls.deleteTree(File(apps, "downloading/$appId"))
|
||||
File(apps, "downloading").listFiles { f -> f.name.startsWith("state_${appId}_") && f.name.endsWith(".patch") }?.forEach { it.delete() }
|
||||
if (manifest != null) acf.delete()
|
||||
forgetJournal(context, appId, guest)
|
||||
StoresState.logLine("Steam: removed the unfinished download of $appId")
|
||||
}
|
||||
}
|
||||
|
||||
internal object SteamBackend : StoreBackend {
|
||||
override val store: Store = Store.STEAM
|
||||
|
||||
override fun signIn(context: Context) {
|
||||
StoresState.logLine("Steam: sign in from the Steam client")
|
||||
}
|
||||
|
||||
override fun signOut(context: Context) = SteamEngine.forget()
|
||||
|
||||
override fun syncLibrary(context: Context, force: Boolean) = SteamStore.syncLibrary(context, force)
|
||||
|
||||
override fun loadShelves(context: Context, force: Boolean) {}
|
||||
|
||||
override fun search(context: Context, query: String): List<CatalogItem> =
|
||||
StoresState.library[store].orEmpty().filter { it.title.contains(query, ignoreCase = true) }
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: File) = SteamStore.restore(context, item)
|
||||
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) {}
|
||||
}
|
||||
@@ -58,17 +58,30 @@ object XboxBackend : StoreBackend {
|
||||
if (cached != null && !cached.needsRefresh(force)) { XboxGamertag.ensure(app); return@Thread }
|
||||
val response = Xodus.run(app, listOf("library", "--json", "--market", market))
|
||||
val licenses = XboxCatalog.access(response, account, market, report = { StoresState.logLine("Xbox: $it") })
|
||||
val products = XboxCatalog.rawProducts(licenses.keys.toList(), market)
|
||||
val cloud = runCatching { XboxCatalog.cloudCatalog(market) }
|
||||
.onFailure { StoresState.logLine("Xbox: cloud lists unavailable (${it.javaClass.simpleName})") }.getOrNull()
|
||||
val games = mergeEditions(products.mapNotNull { XboxCatalog.product(it, licenses, cloud) }).sortedBy { it.title.lowercase() }
|
||||
StoresState.logLine("Xbox: library catalog requested=${licenses.size} returned=${products.size} supported=${games.size} " +
|
||||
"filtered=${products.size - games.size} backend-skipped=${response.optInt("skippedEntitlements")} " +
|
||||
// The PC entitlement list leaves out console purchases and free games; the streaming service lists them.
|
||||
val titles = runCatching { XboxCloudSession.titleList(XboxCloudSession.get(app, account), fresh = true) }
|
||||
.onFailure { StoresState.logLine("Xbox: cloud titles unavailable (${it.javaClass.simpleName})") }.getOrNull()
|
||||
// Without the Game Pass lists an entitled title cannot be told apart from a purchase, so none are added.
|
||||
val added = if (cloud == null) emptyMap<String, String>() else titles?.entitled.orEmpty().filter { it !in licenses }
|
||||
.associateWith { if (it in cloud.gamePass) "gamepass" else "owned" }
|
||||
StoresState.logLine("Xbox: cloud titles=${titles?.ids?.size ?: -1} entitled=${titles?.entitled?.size ?: -1} " +
|
||||
"added=${added.size} (owned ${added.values.count { it == "owned" }}, gamepass ${added.values.count { it == "gamepass" }})")
|
||||
val entitlements = licenses + added
|
||||
val returned = java.util.concurrent.atomic.AtomicInteger()
|
||||
val supported = XboxCatalog.productBatches(entitlements.keys.toList(), market) { batch ->
|
||||
returned.addAndGet(batch.size)
|
||||
batch.mapNotNull { XboxCatalog.product(it, entitlements, cloud) }
|
||||
}
|
||||
val games = mergeEditions(supported).sortedBy { it.title.lowercase() }
|
||||
StoresState.logLine("Xbox: library catalog requested=${entitlements.size} returned=${returned.get()} supported=${supported.size} " +
|
||||
"shown=${games.size} backend-skipped=${response.optInt("skippedEntitlements")} " +
|
||||
"pc=${games.count { it.xboxPc }} cloud=${games.count { it.xboxCloud }} cloud-only=${games.count { !it.xboxPc }} " +
|
||||
"cloud-lists=${cloud?.gamePass?.size ?: -1}/${cloud?.all?.size ?: -1}")
|
||||
synchronized(this) {
|
||||
if (current != generation || StoreAccounts.signedInAs(app, store) != account) return@Thread
|
||||
access = licenses
|
||||
access = entitlements
|
||||
runCatching { XboxLibraryCache.write(app, account, market, games) }
|
||||
.onFailure { StoresState.logLine("Xbox: library cache could not be saved") }
|
||||
}
|
||||
|
||||
@@ -84,10 +84,42 @@ internal object XboxCatalog {
|
||||
return rawProducts(ids, market).mapNotNull { product(it, access) }
|
||||
}
|
||||
|
||||
fun rawProducts(ids: List<String>, market: String = Xodus.market()): List<JSONObject> {
|
||||
return ids.map { it.uppercase() }.filter { productId.matches(it) }.distinct().chunked(25).flatMap { batch ->
|
||||
fun launchArt(id: String, market: String = Xodus.market()): List<String> =
|
||||
rawProducts(listOf(id.uppercase()), market).firstOrNull()?.let(::launchArtUrls).orEmpty()
|
||||
|
||||
internal fun launchArtUrls(json: JSONObject): List<String> {
|
||||
val images = objects(objects(json.optJSONArray("LocalizedProperties")).firstOrNull()?.optJSONArray("Images"))
|
||||
val order = listOf("SuperHeroArt", "TitledHeroArt", "Screenshot", "Hero")
|
||||
return images.filter { it.optString("ImagePurpose") in order }
|
||||
.sortedBy { order.indexOf(it.optString("ImagePurpose")) }
|
||||
.mapNotNull { image ->
|
||||
val raw = image.optString("Uri")
|
||||
val url = if (raw.startsWith("//")) "https:$raw" else raw
|
||||
runCatching { java.net.URI(url) }.getOrNull()?.takeIf {
|
||||
it.scheme == "https" && it.host in setOf("store-images.s-microsoft.com", "store-images.microsoft.com") && it.userInfo == null && it.port == -1
|
||||
}?.toString()
|
||||
}.distinct().take(12)
|
||||
}
|
||||
|
||||
fun rawProducts(ids: List<String>, market: String = Xodus.market()): List<JSONObject> = productBatches(ids, market) { it }
|
||||
|
||||
// 25 ids per request, up to 4 requests at a time; each batch is mapped as it arrives (a whole library of raw entries is large).
|
||||
fun <T> productBatches(ids: List<String>, market: String = Xodus.market(), map: (List<JSONObject>) -> List<T>): List<T> {
|
||||
val batches = ids.map { it.uppercase() }.filter { productId.matches(it) }.distinct().chunked(25)
|
||||
fun fetchBatch(batch: List<String>): List<T> {
|
||||
val body = get("https://displaycatalog.mp.microsoft.com/v7.0/products?bigIds=${batch.joinToString(",")}&market=$market&languages=en-us,neutral")
|
||||
objects(body.optJSONArray("Products")).filter { it.optString("ProductId").uppercase() in batch }
|
||||
return map(objects(body.optJSONArray("Products")).filter { it.optString("ProductId").uppercase() in batch })
|
||||
}
|
||||
if (batches.size <= 1) return batches.flatMap(::fetchBatch)
|
||||
val pool = java.util.concurrent.Executors.newFixedThreadPool(4)
|
||||
try {
|
||||
val tasks = batches.map { batch -> pool.submit(java.util.concurrent.Callable { fetchBatch(batch) }) }
|
||||
return tasks.flatMap { task ->
|
||||
try { task.get(60, java.util.concurrent.TimeUnit.SECONDS) }
|
||||
catch (e: java.util.concurrent.ExecutionException) { throw e.cause ?: e }
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,16 +212,28 @@ val CatalogItem.xboxPc: Boolean get() = extra["pc"] != "0"
|
||||
val CatalogItem.xboxCloud: Boolean get() = extra["cloud"] == "1"
|
||||
val CatalogItem.xboxCloudId: String get() = extra["cloudId"]?.takeIf { it.isNotEmpty() } ?: id
|
||||
|
||||
// One card per title: a cloud-only edition folds into the PC card (which then streams, and counts as owned when
|
||||
// the cloud edition is); cloud-only editions with the same title become one card, owned first.
|
||||
internal fun mergeEditions(games: List<CatalogItem>): List<CatalogItem> {
|
||||
fun key(title: String) = title.lowercase().replace(Regex("[^a-z0-9]+"), "")
|
||||
fun key(title: String): String {
|
||||
val lower = title.lowercase()
|
||||
val letters = StringBuilder().apply { lower.codePoints().filter { Character.isLetterOrDigit(it) }.forEach { appendCodePoint(it) } }
|
||||
return letters.toString().ifEmpty { lower.trim() }
|
||||
}
|
||||
val pcKeys = games.filter { it.xboxPc }.map { key(it.title) }.toSet()
|
||||
val cloudOnly = games.filter { !it.xboxPc && it.xboxCloud }.groupBy { key(it.title) }
|
||||
val folded = HashSet<String>()
|
||||
val merged = games.map { game ->
|
||||
if (!game.xboxPc || game.xboxCloud) game
|
||||
else cloudOnly[key(game.title)]?.firstOrNull()?.let { console ->
|
||||
folded.add(console.id)
|
||||
game.copy(extra = game.extra + mapOf("cloud" to "1", "cloudId" to console.id))
|
||||
} ?: game
|
||||
.mapValues { (_, list) -> list.sortedByDescending { it.owned }.first() }
|
||||
return games.mapNotNull { game ->
|
||||
val console = cloudOnly[key(game.title)]
|
||||
when {
|
||||
!game.xboxPc -> game.takeIf { key(game.title) !in pcKeys && (console == null || console === game) }
|
||||
console == null -> game
|
||||
else -> {
|
||||
val cloudId = if (game.xboxCloud) game.extra["cloudId"].orEmpty() else console.id
|
||||
val merged = game.copy(extra = game.extra + mapOf("cloud" to "1", "cloudId" to cloudId))
|
||||
if (console.owned && !game.owned) merged.copy(owned = true, subscription = false, extra = merged.extra + ("access" to "owned"))
|
||||
else merged
|
||||
}
|
||||
}
|
||||
}
|
||||
return merged.filter { it.id !in folded }
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import android.content.Intent
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.view.KeyEvent
|
||||
import android.view.WindowManager
|
||||
import android.webkit.JavascriptInterface
|
||||
@@ -47,6 +48,8 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
||||
private lateinit var root: FrameLayout
|
||||
private var web: WebView? = null
|
||||
private var notice: LinearLayout? = null
|
||||
private lateinit var art: XboxLaunchArt
|
||||
private lateinit var artStatus: TextView
|
||||
private val worker = Executors.newSingleThreadExecutor()
|
||||
private val signalling = Executors.newCachedThreadPool()
|
||||
@Volatile private var session: XboxCloudSession.Session? = null
|
||||
@@ -68,15 +71,24 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
||||
root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
|
||||
setContentView(root)
|
||||
val requested = intent.getStringExtra("product").orEmpty()
|
||||
art = XboxLaunchArt(this) { diag("cloud player $it") }
|
||||
root.addView(art.view(intent.getStringExtra("title").orEmpty()) { cancelLaunch() }, FrameLayout.LayoutParams(-1, -1))
|
||||
artStatus = TextView(this).apply {
|
||||
setTextColor(Color.WHITE); textSize = 16f; gravity = Gravity.CENTER; setShadowLayer(10f, 0f, 0f, Color.BLACK); visibility = View.GONE
|
||||
}
|
||||
root.addView(artStatus, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM).apply { bottomMargin = 120 })
|
||||
art.load(requested)
|
||||
showNotice("Signing in to Xbox Cloud Gaming…", withButtons = false)
|
||||
worker.execute {
|
||||
val result = runCatching {
|
||||
val account = StoreAccounts.signedInAs(applicationContext, Store.XBOX) ?: error("Sign in to the Xbox store first.")
|
||||
val cached = XboxLibraryCache.read(applicationContext, account, Xodus.market())?.games?.firstOrNull { it.id == requested }
|
||||
val product = cached?.extra?.get("cloudId")?.takeIf { it.isNotEmpty() } ?: requested
|
||||
webUrl = XboxCatalog.cloudUrl(requested, cached?.title ?: intent.getStringExtra("title").orEmpty(), product)
|
||||
val name = cached?.title ?: intent.getStringExtra("title").orEmpty()
|
||||
webUrl = XboxCatalog.cloudUrl(requested, name, product)
|
||||
val active = XboxCloudSession.get(applicationContext, account)
|
||||
val title = XboxCloudSession.titles(active)[product] ?: error("This game can't be streamed with this account here.")
|
||||
val title = XboxCloudSession.titleFor(active, product, name) { diag("cloud player: $it") }
|
||||
?: error("This game can't be streamed with this account here.")
|
||||
settings = XboxCloudSettings.load(applicationContext)
|
||||
startedWith = settings
|
||||
session = active.forStream(settings.region, settings.osName); titleId = title
|
||||
@@ -86,6 +98,7 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
||||
if (closed) return@runOnUiThread
|
||||
result.onSuccess { openPlayer() }.onFailure {
|
||||
diag("cloud player not started: ${it.javaClass.simpleName}: ${it.message?.take(160)}")
|
||||
hideArt()
|
||||
showNotice(it.message ?: "Xbox Cloud Gaming could not start.", withButtons = true)
|
||||
}
|
||||
}
|
||||
@@ -130,6 +143,12 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
||||
fun call(id: Int, op: String, arg: String) {
|
||||
signalling.execute {
|
||||
val reply = runCatching { handle(op, arg) }.getOrElse { XboxCloudSession.Reply(0, it.javaClass.simpleName) }
|
||||
if (closed && op == "start") {
|
||||
val active = session; val path = sessionPath
|
||||
if (active != null && path != null) runCatching { XboxCloudSession.request(active, "DELETE", "/$path") }
|
||||
.onSuccess { diag("cloud player cancelled: session closed ${it.status}") }
|
||||
return@execute
|
||||
}
|
||||
if (reply.status !in 200..299) diag("cloud player $op: ${reply.status} ${reply.body.take(300)}")
|
||||
else if (op != "state" && op != "keepalive") diag("cloud player $op: ${reply.status}")
|
||||
runOnUiThread { web?.evaluateJavascript("window.__ddResolve($id, ${reply.status}, ${JSONObject.quote(reply.body)})", null) }
|
||||
@@ -137,12 +156,24 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
@JavascriptInterface
|
||||
fun status(text: String) { android.util.Log.i("XboxCloudPlayer", "status: ${text.take(120)}") }
|
||||
fun status(text: String) {
|
||||
android.util.Log.i("XboxCloudPlayer", "status: ${text.take(120)}")
|
||||
if (art.shown) runOnUiThread { if (art.shown) { artStatus.text = text; artStatus.visibility = if (text.isEmpty()) View.GONE else View.VISIBLE } }
|
||||
}
|
||||
|
||||
@JavascriptInterface
|
||||
fun playing() {
|
||||
diag("cloud player streaming")
|
||||
runOnUiThread { web?.requestFocus() }
|
||||
runOnUiThread {
|
||||
web?.requestFocus()
|
||||
if (art.shown) { web?.evaluateJavascript(FIRST_FRAME_JS, null); root.postDelayed({ hideArt() }, 6000) }
|
||||
}
|
||||
}
|
||||
|
||||
@JavascriptInterface
|
||||
fun firstFrame() {
|
||||
if (art.shown) diag("cloud player first frame")
|
||||
hideArt()
|
||||
}
|
||||
|
||||
@JavascriptInterface
|
||||
@@ -154,6 +185,7 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
||||
@JavascriptInterface
|
||||
fun failed(stage: String, detail: String) {
|
||||
diag("cloud player failed at ${stage.take(40)}: ${detail.take(300)}")
|
||||
hideArt()
|
||||
runOnUiThread { if (!closed) showNotice("The stream could not start ($stage).", withButtons = true) }
|
||||
}
|
||||
}
|
||||
@@ -164,6 +196,13 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
||||
return signals.op(op, arg).also { sessionPath = signals.path }
|
||||
}
|
||||
|
||||
private fun hideArt() {
|
||||
art.hide()
|
||||
runOnUiThread { artStatus.visibility = View.GONE }
|
||||
}
|
||||
|
||||
private fun cancelLaunch() { if (!isFinishing) { diag("cloud player launch cancelled"); finish() } }
|
||||
|
||||
private fun showNotice(text: String, withButtons: Boolean) {
|
||||
notice?.let { root.removeView(it) }
|
||||
val box = LinearLayout(this).apply {
|
||||
@@ -264,6 +303,10 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
if (art.shown && (event.keyCode == KeyEvent.KEYCODE_BUTTON_B || event.keyCode == KeyEvent.KEYCODE_BACK)) {
|
||||
if (event.action == KeyEvent.ACTION_UP) cancelLaunch()
|
||||
return true
|
||||
}
|
||||
if (notice == null && guideKey(event)) return true
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BACK) {
|
||||
if (event.action == KeyEvent.ACTION_UP) { if (notice == null) openMenu() else finish() }
|
||||
@@ -379,6 +422,10 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
||||
|
||||
companion object {
|
||||
private const val DOUBLE_PRESS_MS = 350L
|
||||
// Calls DDCloud.firstFrame() once the page's video has decoded a frame (or after 6 s).
|
||||
private const val FIRST_FRAME_JS = "(function(){var t=Date.now();(function poll(){var v=document.querySelector('video');" +
|
||||
"var n=v&&v.getVideoPlaybackQuality?v.getVideoPlaybackQuality().totalVideoFrames:0;" +
|
||||
"if(n>0||(v&&v.currentTime>0)||Date.now()-t>6000){DDCloud.firstFrame();return;}setTimeout(poll,100);})();})()"
|
||||
|
||||
fun intent(context: Context, productId: String, title: String): Intent = Intent(context, XboxCloudPlayerActivity::class.java)
|
||||
.putExtra("product", productId.uppercase()).putExtra("title", title)
|
||||
|
||||
@@ -35,7 +35,7 @@ internal object XboxCloudSession {
|
||||
json.optString("userToken").takeIf { !json.isNull("userToken") && it.isNotEmpty() }, System.currentTimeMillis() + seconds * 1000).also { cached = it }
|
||||
}
|
||||
|
||||
fun clear() { cached = null; titleIds = null }
|
||||
fun clear() { cached = null; titleList = null; looked = null }
|
||||
|
||||
fun fromMainProcess(app: Context, account: String, timeoutSeconds: Long = 90): Session? {
|
||||
cached?.takeIf { it.account == account && it.fresh }?.let { return it }
|
||||
@@ -61,21 +61,64 @@ internal object XboxCloudSession {
|
||||
b.getString("baseUri").orEmpty(), regions, b.getString("userToken"), b.getLong("expiresAt"))
|
||||
}
|
||||
|
||||
@Volatile private var titleIds: Pair<String, Map<String, String>>? = null
|
||||
class Titles(val ids: Map<String, String>, val entitled: Set<String>)
|
||||
|
||||
fun titles(session: Session): Map<String, String> {
|
||||
titleIds?.takeIf { it.first == session.account }?.let { return it.second }
|
||||
@Volatile private var titleList: Pair<String, Titles>? = null
|
||||
|
||||
fun titles(session: Session): Map<String, String> = titleList(session).ids
|
||||
|
||||
// Entitled = details.hasEntitlement or isFreeInStore, as Greenlight's xcloud.ts by unknownskl (MIT).
|
||||
fun titleList(session: Session, fresh: Boolean = false): Titles {
|
||||
if (!fresh) titleList?.takeIf { it.first == session.account }?.let { return it.second }
|
||||
val reply = request(session, "GET", "/v2/titles")
|
||||
check(reply.status == 200) { "Xbox Cloud Gaming answered ${reply.status}" }
|
||||
val results = JSONObject(reply.body).optJSONArray("results") ?: JSONArray()
|
||||
val map = (0 until results.length()).mapNotNull { index ->
|
||||
val row = results.optJSONObject(index) ?: return@mapNotNull null
|
||||
val product = row.optJSONObject("details")?.optString("productId")?.uppercase().orEmpty()
|
||||
val ids = LinkedHashMap<String, String>()
|
||||
val entitled = LinkedHashSet<String>()
|
||||
for (index in 0 until results.length()) {
|
||||
val row = results.optJSONObject(index) ?: continue
|
||||
val details = row.optJSONObject("details")
|
||||
val product = details?.optString("productId")?.uppercase().orEmpty()
|
||||
val title = row.optString("titleId")
|
||||
if (product.matches(Regex("[A-Z0-9]{12}")) && title.isNotBlank() && title.length <= 64) product to title else null
|
||||
}.toMap()
|
||||
titleIds = session.account to map
|
||||
return map
|
||||
if (!product.matches(Regex("[A-Z0-9]{12}")) || title.isBlank() || title.length > 64) continue
|
||||
ids.putIfAbsent(product, title)
|
||||
if (details?.optBoolean("hasEntitlement") == true || details?.optBoolean("isFreeInStore") == true) entitled += product
|
||||
}
|
||||
return Titles(ids, entitled).also { titleList = session.account to it }
|
||||
}
|
||||
|
||||
@Volatile private var looked: Pair<String, MutableMap<String, String>>? = null
|
||||
|
||||
// Lookup by product id (POST /v2/titles with alternateIds) as Better xCloud's getTitleInfo (MIT).
|
||||
fun titleFor(session: Session, productId: String, name: String = "", log: (String) -> Unit = {}): String? {
|
||||
val product = productId.uppercase()
|
||||
val list = titles(session)
|
||||
list[product]?.let { return it }
|
||||
val cache = looked?.takeIf { it.first == session.account }?.second ?: HashMap<String, String>().also { looked = session.account to it }
|
||||
cache[product]?.let { return it }
|
||||
val body = JSONObject().put("alternateIds", JSONArray().put(product)).put("alternateIdType", "productId").toString()
|
||||
val reply = runCatching { request(session, "POST", "/v2/titles", body) }.getOrNull()
|
||||
val rows = reply?.takeIf { it.status == 200 }?.let { runCatching { JSONObject(it.body).optJSONArray("results") }.getOrNull() }
|
||||
val row = rows?.optJSONObject(0)
|
||||
val title = row?.optString("titleId").orEmpty()
|
||||
val rowProduct = row?.optJSONObject("details")?.optString("productId")?.uppercase().orEmpty()
|
||||
log("title lookup $product: http ${reply?.status ?: -1}, results ${rows?.length() ?: -1}, title ${title.ifEmpty { "-" }}, product ${rowProduct.ifEmpty { "-" }}")
|
||||
if (title.isNotBlank() && title.length <= 64) { cache[product] = title; return title }
|
||||
val key = nameKey(name)
|
||||
if (key.length >= 4) {
|
||||
val byName = list.values.filter { it.uppercase() == key }.distinct()
|
||||
log("title by name $key: ${byName.joinToString().ifEmpty { "none" }}")
|
||||
if (byName.size == 1) { cache[product] = byName[0]; return byName[0] }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private val EDITION_WORDS = Regex("(STANDARD|DELUXE|PREMIUM|ULTIMATE|GOLD|COMPLETE|DEFINITIVE|ENHANCED|ANNIVERSARY|GAMEOFTHEYEAR|GOTY)?EDITION$|GAMEPREVIEW$|FORWINDOWS(10)?$|XBOXSERIESXS$|XBOXONE$|PC$")
|
||||
|
||||
internal fun nameKey(name: String): String {
|
||||
var key = name.uppercase().replace(Regex("[^A-Z0-9]"), "")
|
||||
repeat(3) { key = key.replace(EDITION_WORDS, "") }
|
||||
return key
|
||||
}
|
||||
|
||||
class Reply(val status: Int, val body: String)
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import android.app.Activity
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.Crossfade
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.LinearEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.onClick
|
||||
import androidx.compose.ui.semantics.role
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import coil.compose.AsyncImage
|
||||
import coil.request.ImageRequest
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreAccounts
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
// The game's art as a slow slideshow while a cloud stream connects, until the first video frame.
|
||||
// From Even Better Xcloud (BannerCloud) 7ec2a75.
|
||||
internal class XboxLaunchArt(private val activity: Activity, private val log: (String) -> Unit) {
|
||||
private val urls = mutableStateListOf<String>()
|
||||
private var visible by mutableStateOf(true)
|
||||
@Volatile var shown = true
|
||||
private set
|
||||
|
||||
fun view(title: String, onCancel: () -> Unit): ComposeView = ComposeView(activity).apply {
|
||||
setContent { DroidDeckTheme { LaunchArt(urls, title, visible, onCancel) } }
|
||||
}
|
||||
|
||||
fun load(product: String) {
|
||||
if (product.isEmpty()) return
|
||||
val app = activity.applicationContext
|
||||
Thread({
|
||||
runCatching {
|
||||
val account = StoreAccounts.signedInAs(app, Store.XBOX) ?: return@runCatching
|
||||
val game = XboxLibraryCache.read(app, account, Xodus.market())?.games?.firstOrNull { it.id == product }
|
||||
game?.imageUrl?.let { url -> activity.runOnUiThread { if (urls.isEmpty()) urls.add(url) } }
|
||||
val more = XboxCatalog.launchArt(product)
|
||||
if (more.isNotEmpty()) activity.runOnUiThread { urls.addAll(more.filter { it !in urls }) }
|
||||
}.onFailure { log("launch art: ${it.javaClass.simpleName}") }
|
||||
}, "launch-art").start()
|
||||
}
|
||||
|
||||
fun hide() {
|
||||
shown = false
|
||||
activity.runOnUiThread { visible = false }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LaunchArt(images: List<String>, title: String, visible: Boolean, onCancel: () -> Unit) {
|
||||
AnimatedVisibility(visible, enter = fadeIn(tween(400)), exit = fadeOut(tween(700))) {
|
||||
Box(Modifier.fillMaxSize().background(Color.Black)) {
|
||||
var index by remember { mutableIntStateOf(0) }
|
||||
LaunchedEffect(images.size) {
|
||||
while (true) {
|
||||
delay(SLIDE_MS)
|
||||
if (images.size > 1) index = (index + 1) % images.size
|
||||
}
|
||||
}
|
||||
Crossfade(targetState = images.getOrNull(index % images.size.coerceAtLeast(1)), animationSpec = tween(1400),
|
||||
label = "launch-art") { url ->
|
||||
if (url != null) Slide(url, index)
|
||||
}
|
||||
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(
|
||||
0f to Color(0x66000000), 0.45f to Color(0x22000000), 0.78f to Color(0xB3000000), 1f to Color(0xF2000000))))
|
||||
Text(title, style = MaterialTheme.typography.headlineSmall, color = Color.White, maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.align(Alignment.BottomStart).padding(start = 40.dp, end = 220.dp, bottom = 34.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.align(Alignment.BottomEnd).padding(end = 40.dp, bottom = 30.dp)
|
||||
.clip(RoundedCornerShape(50)).background(Color(0x99000000))
|
||||
.pointerInput(Unit) { detectTapGestures { onCancel() } }
|
||||
.semantics(mergeDescendants = true) { role = Role.Button; onClick { onCancel(); true } }
|
||||
.padding(start = 8.dp, end = 18.dp, top = 8.dp, bottom = 8.dp)) {
|
||||
Box(Modifier.size(28.dp).clip(CircleShape).background(Color(0xFFE5484D)), contentAlignment = Alignment.Center) {
|
||||
Text("B", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 15.sp)
|
||||
}
|
||||
Text(stringResource(R.string.common_cancel), color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Slide(url: String, index: Int) {
|
||||
val ctx = LocalContext.current
|
||||
val progress = remember(url) { Animatable(0f) }
|
||||
LaunchedEffect(url) { progress.animateTo(1f, tween((SLIDE_MS + 1600).toInt(), easing = LinearEasing)) }
|
||||
val dir = if (index % 2 == 0) 1f else -1f
|
||||
AsyncImage(
|
||||
model = ImageRequest.Builder(ctx).data(url).crossfade(500).build(),
|
||||
contentDescription = null, contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxSize().graphicsLayer {
|
||||
val p = progress.value
|
||||
val s = 1.06f + 0.10f * p
|
||||
scaleX = s; scaleY = s
|
||||
translationX = dir * (p - 0.5f) * size.width * 0.04f
|
||||
})
|
||||
}
|
||||
|
||||
private const val SLIDE_MS = 5200L
|
||||
@@ -5,6 +5,7 @@ import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Color
|
||||
import android.media.AudioAttributes
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.VibrationEffect
|
||||
@@ -75,6 +76,7 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
||||
@Volatile private var connectedOnce = false
|
||||
@Volatile private var endedInBackground = false
|
||||
private var backgroundEnd: Runnable? = null
|
||||
private lateinit var art: XboxLaunchArt
|
||||
private var notice: androidx.compose.ui.platform.ComposeView? = null
|
||||
@Volatile private var regionNames = emptyList<String>()
|
||||
@Volatile private var serverName: String? = null
|
||||
@@ -103,7 +105,10 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
||||
root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
|
||||
surfaceView = SurfaceView(this)
|
||||
root.addView(surfaceView, FrameLayout.LayoutParams(-1, -1))
|
||||
status = TextView(this).apply { setTextColor(Color.WHITE); textSize = 16f; gravity = Gravity.CENTER }
|
||||
art = XboxLaunchArt(this) { log(it) }
|
||||
root.addView(art.view(intent.getStringExtra("title").orEmpty()) { cancelLaunch() }, FrameLayout.LayoutParams(-1, -1))
|
||||
art.load(intent.getStringExtra("product").orEmpty())
|
||||
status = TextView(this).apply { setTextColor(Color.WHITE); textSize = 16f; gravity = Gravity.CENTER; setShadowLayer(10f, 0f, 0f, Color.BLACK) }
|
||||
root.addView(status, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM).apply { bottomMargin = 120 })
|
||||
overlay = TextView(this).apply {
|
||||
setTextColor(Color.WHITE); textSize = 12f; typeface = android.graphics.Typeface.MONOSPACE
|
||||
@@ -118,6 +123,7 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
||||
|
||||
val egl = EglBase.create().also { eglBase = it }
|
||||
val nativeVideo = XboxNativeVideo(this, egl) { log(it) }.also { video = it }
|
||||
nativeVideo.onFirstFrame = { hideArt() }
|
||||
surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {}
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
|
||||
@@ -137,9 +143,12 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
||||
|
||||
private fun log(text: String) = com.droiddeck.launcher.stores.StoresState.logLine("Xbox: native player: ${text.take(240)}")
|
||||
private fun show(text: String) = runOnUiThread { status.text = text; status.visibility = if (text.isEmpty()) android.view.View.GONE else android.view.View.VISIBLE }
|
||||
private fun hideArt() { if (art.shown) { art.hide(); show("") } }
|
||||
private fun cancelLaunch() { if (!isFinishing) { log("launch cancelled"); finish() } }
|
||||
|
||||
private fun fail(stage: String, detail: String) {
|
||||
log("failed at $stage: $detail")
|
||||
art.hide()
|
||||
if (closed) return
|
||||
if (connectedOnce) showNotice("The connection to the cloud console was lost",
|
||||
"The stream stopped reaching this device ($detail). Restart the stream to play again: the game starts over, " +
|
||||
@@ -232,12 +241,14 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
||||
val active = (shared ?: XboxCloudSession.get(applicationContext, account)).forStream(settings.region, settings.osName)
|
||||
regionNames = active.regionList.map { it.name }
|
||||
serverName = active.regionList.firstOrNull { it.baseUri == active.baseUri }?.name
|
||||
val title = XboxCloudSession.titles(active)[product] ?: error("This game can't be streamed with this account here.")
|
||||
val title = XboxCloudSession.titleFor(active, product, cached?.title ?: intent.getStringExtra("title").orEmpty()) { log(it) }
|
||||
?: error("This game can't be streamed with this account here.")
|
||||
val signals = XboxCloudSignalling(active, title, settings).also { signalling = it }
|
||||
log("$product -> $title, region ${java.net.URI(active.baseUri).host}, frame gen ${settings.frameGen}")
|
||||
|
||||
show("Starting the game on Xbox Cloud Gaming…")
|
||||
expect("start", signals.start())
|
||||
if (closed) { runCatching { signals.stop() }.onSuccess { log("cancelled: session closed ${it?.status}") }; return }
|
||||
var connected = false
|
||||
var waited = 0
|
||||
while (!closed) {
|
||||
@@ -270,7 +281,15 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
||||
log("latency: instant input ${settings.instantInput}, small buffer ${settings.smallBuffer}, fast decoder ${settings.fastDecoder}, " +
|
||||
"zero-copy ${zeroSurface != null}")
|
||||
val f = PeerConnectionFactory.builder()
|
||||
.setAudioDeviceModule(JavaAudioDeviceModule.builder(applicationContext).createAudioDeviceModule())
|
||||
// WebRTC defaults to voice-call audio (mono, speaker/earpiece only); game audio follows
|
||||
// the normal output (HDMI, USB, Bluetooth) and keeps the stream's stereo.
|
||||
.setAudioDeviceModule(JavaAudioDeviceModule.builder(applicationContext)
|
||||
.setAudioAttributes(AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_GAME)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE)
|
||||
.build())
|
||||
.setUseStereoOutput(true)
|
||||
.createAudioDeviceModule())
|
||||
.setVideoDecoderFactory(org.webrtc.DroidDeckLowLatencyDecoderFactory(egl.eglBaseContext, settings.fastDecoder, zeroSurface) { zeroCopyFrames++ }
|
||||
.also { decoders = it })
|
||||
.setVideoEncoderFactory(DefaultVideoEncoderFactory(egl.eglBaseContext, true, true))
|
||||
@@ -365,7 +384,7 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
||||
when (state) {
|
||||
PeerConnection.PeerConnectionState.CONNECTED -> {
|
||||
connectedOnce = true
|
||||
show("")
|
||||
if (art.shown) root.postDelayed({ hideArt() }, 6000) else show("")
|
||||
video?.setFpsTarget(settings.fpsTarget)
|
||||
video?.setFrameGeneration(effectiveFrameGen())
|
||||
}
|
||||
@@ -427,6 +446,10 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
if (art.shown && (event.keyCode == KeyEvent.KEYCODE_BUTTON_B || event.keyCode == KeyEvent.KEYCODE_BACK)) {
|
||||
if (event.action == KeyEvent.ACTION_UP) cancelLaunch()
|
||||
return true
|
||||
}
|
||||
if (isGuide(event)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
val pending = pendingNexus
|
||||
|
||||
@@ -54,6 +54,7 @@ internal class XboxNativeVideo(private val context: Context, eglBase: EglBase, p
|
||||
private var nextDueNs = 0L
|
||||
@Volatile var frames = 0L
|
||||
private set
|
||||
@Volatile var onFirstFrame: (() -> Unit)? = null
|
||||
|
||||
fun setSurface(target: Surface?, width: Int, height: Int, displayRefreshHz: Float) = synchronized(lock) {
|
||||
refreshHz = displayRefreshHz
|
||||
@@ -126,7 +127,10 @@ internal class XboxNativeVideo(private val context: Context, eglBase: EglBase, p
|
||||
if (nextDueNs == 0L || now - nextDueNs > interval) nextDueNs = now
|
||||
if (now + 4_000_000L < nextDueNs) true else { nextDueNs += interval; false }
|
||||
}
|
||||
if (attached && buffer != null && !skip) { WaylandCompositor.nativeStreamFrame(buffer); frames++ }
|
||||
if (attached && buffer != null && !skip) {
|
||||
WaylandCompositor.nativeStreamFrame(buffer); frames++
|
||||
onFirstFrame?.let { onFirstFrame = null; it() }
|
||||
}
|
||||
buffer?.close()
|
||||
held.addLast(image)
|
||||
while (held.size > 2) held.removeFirst().close()
|
||||
|
||||
@@ -273,7 +273,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
var text by remember { mutableStateOf("") }
|
||||
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
|
||||
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
|
||||
var source by remember { mutableStateOf(AddonSource.WOWI) }
|
||||
var source by remember(curseForge != null) { mutableStateOf(if (curseForge != null) AddonSource.CURSE else AddonSource.WOWI) }
|
||||
val curse = if (source == AddonSource.CURSE && link != null) curseForge else null
|
||||
LaunchedEffect(link) { link?.refresh() }
|
||||
var notice by remember { mutableStateOf<Int?>(null) }
|
||||
@@ -425,8 +425,8 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
}
|
||||
val sourceChip: @Composable () -> Unit = {
|
||||
if (curseForge != null) BrowseDropdown(sourceName) { first, done ->
|
||||
MenuItem(stringResource(R.string.addons_source_wowi), source == AddonSource.WOWI, focusRequester = first) { source = AddonSource.WOWI; done() }
|
||||
MenuItem(stringResource(R.string.addons_source_curse), source == AddonSource.CURSE) { source = AddonSource.CURSE; done() }
|
||||
MenuItem(stringResource(R.string.addons_source_wowi), curse == null, focusRequester = first) { source = AddonSource.WOWI; done() }
|
||||
MenuItem(stringResource(R.string.addons_source_curse), curse != null) { source = AddonSource.CURSE; done() }
|
||||
}
|
||||
}
|
||||
val categoryChip: @Composable () -> Unit = {
|
||||
|
||||
@@ -103,6 +103,7 @@ class FrontEndState(
|
||||
val desktopPresent: Boolean = desktopInstalled,
|
||||
val offlineAccount: String?,
|
||||
val offline: Boolean,
|
||||
val offlineAuto: Boolean = true,
|
||||
val frameGenLabel: String,
|
||||
val romsDir: String?,
|
||||
val logsEnabled: Boolean,
|
||||
@@ -273,6 +274,7 @@ class FrontEndActions(
|
||||
val onClearLogs: () -> Unit = {},
|
||||
val onResetSettings: () -> Unit = {},
|
||||
val onOffline: () -> Unit,
|
||||
val onOfflineAuto: () -> Unit = {},
|
||||
val onPageBack: () -> Unit = {},
|
||||
val onTheme: (String) -> Unit = {},
|
||||
val onLanguage: (String) -> Unit = {},
|
||||
@@ -840,6 +842,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
|
||||
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
|
||||
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
|
||||
com.droiddeck.launcher.stores.steam.SteamStore.picking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.steam.SteamStore.picking = null } } }
|
||||
StepsLayer(screenAt)
|
||||
UiZooSheet()
|
||||
SessionDrawerPreview(s.secondScreenDisplays)
|
||||
|
||||
@@ -56,6 +56,7 @@ import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -139,6 +140,7 @@ import androidx.compose.foundation.layout.offset
|
||||
internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?) {
|
||||
fun game(games: List<Library.SteamGame>): Library.SteamGame? = when {
|
||||
appId != null -> games.firstOrNull { it.appId == appId }
|
||||
store == Store.STEAM && storeId != null -> games.firstOrNull { Library.fromSteamClient(it) && it.appId.toString() == storeId }
|
||||
store != null && storeId != null -> games.firstOrNull { it.source == store.id && it.storeId == storeId }
|
||||
else -> null
|
||||
}
|
||||
@@ -182,7 +184,7 @@ internal fun GameDetail(
|
||||
if (nothing) return
|
||||
val source = game?.source ?: store?.id ?: Library.SOURCE_STEAM
|
||||
val title = game?.name ?: item?.title ?: installed?.sidecar?.title ?: id.orEmpty()
|
||||
val favoriteKey = if (store != null && id != null) "${store.id}:$id" else game?.let { GameRef.key(it) } ?: key
|
||||
val favoriteKey = if (store == Store.STEAM && id != null) "app:$id" else if (store != null && id != null) "${store.id}:$id" else game?.let { GameRef.key(it) } ?: key
|
||||
val scores = if (source != Library.ADDED) rememberGameScores(title.takeIf { it.isNotBlank() && it != id }) else null
|
||||
val achievements = remember(store, id, item?.accessible, installed) {
|
||||
when {
|
||||
@@ -1068,8 +1070,36 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
|
||||
runCatching { CurseForgeApp.byFolder(link.installed(context, target, scanKey)) }.getOrDefault(emptyMap())
|
||||
}
|
||||
}
|
||||
val progress = remember(target.addOns) { mutableStateMapOf<String, Int>() }
|
||||
val curseOf = { item: WowAddons.Installed -> link?.let { l -> managed[item.name.lowercase()]?.let { it to l } } }
|
||||
val outdated = names.filter { item -> curseOf(item)?.first?.update ?: (updates[item.name] != null) }
|
||||
val scope = rememberCoroutineScope()
|
||||
if (targets.size > 1) SectionLabel(target.flavor)
|
||||
MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target }
|
||||
if (outdated.size > 1 && !SessionState.running) MenuItem(
|
||||
stringResource(R.string.store_update_all, outdated.size), checked = false, enabled = progress.isEmpty(),
|
||||
) {
|
||||
val plan = outdated.groupBy { item -> curseOf(item)?.first?.id?.let { "curse:$it" } ?: "folder:${item.name}" }.values.map { group ->
|
||||
Triple(group.map { it.name }, updates[group.first().name], curseOf(group.first()))
|
||||
}
|
||||
plan.forEach { (folders) -> folders.forEach { progress[it] = 0 } }
|
||||
val owned = plan.flatMap { it.first }.toMutableSet()
|
||||
scope.launch {
|
||||
try {
|
||||
plan.forEach { (folders, wowi, curse) ->
|
||||
val name = folders.first()
|
||||
val (message, ok) = updateAddon(context, name, wowi.takeIf { curse == null }, target, curse) { pct ->
|
||||
scope.launch { folders.forEach { progress[it] = pct } }
|
||||
}
|
||||
folders.forEach { progress.remove(it) }
|
||||
owned.removeAll(folders.toSet())
|
||||
if (!ok && message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
} finally {
|
||||
owned.forEach { progress.remove(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
MenuItem(
|
||||
stringResource(R.string.games_import_addons), checked = false,
|
||||
detail = pluralStringResource(R.plurals.games_addons_count, names.size, names.size),
|
||||
@@ -1078,7 +1108,7 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
|
||||
target.addOns.mkdirs()
|
||||
a.onBrowseFiles(target.addOns)
|
||||
}
|
||||
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a, link?.let { l -> managed[item.name.lowercase()]?.let { it to l } }) } }
|
||||
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a, progress, curseOf(item)) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1132,12 +1162,12 @@ private fun CurseForgeEntry(a: FrontEndActions) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, curse: Pair<CurseForgeApp.Project, CurseLink>? = null) {
|
||||
internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, progresses: MutableMap<String, Int>, curse: Pair<CurseForgeApp.Project, CurseLink>? = null) {
|
||||
val name = item.name
|
||||
val update = wowiUpdate.takeIf { curse == null }
|
||||
val outdated = update != null || curse?.first?.update == true
|
||||
var asking by remember(target.addOns, name) { mutableStateOf(false) }
|
||||
var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) }
|
||||
val progress = progresses[name]
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val delete = stringResource(R.string.common_delete)
|
||||
@@ -1152,31 +1182,39 @@ internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Add
|
||||
)
|
||||
}
|
||||
if (outdated && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
|
||||
progress = 0
|
||||
progresses[name] = 0
|
||||
scope.launch {
|
||||
val message = withContext(Dispatchers.IO) {
|
||||
if (curse != null) {
|
||||
val (project, link) = curse
|
||||
val done = runCatching { link.change(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
||||
WowAddons.changed()
|
||||
if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)
|
||||
} else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first }
|
||||
try {
|
||||
val message = updateAddon(context, name, update, target, curse) { pct -> scope.launch { progresses[name] = pct } }.first
|
||||
if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
} finally {
|
||||
progresses.remove(name)
|
||||
}
|
||||
progress = null
|
||||
if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
|
||||
if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true, enabled = progress == null) { asking = true }
|
||||
}
|
||||
if (asking) ConfirmDialog(
|
||||
title = if (curse != null) stringResource(R.string.stores_uninstall_title, name) else stringResource(R.string.games_delete_addon_title, name),
|
||||
text = stringResource(R.string.games_delete_addon_body),
|
||||
confirm = if (curse != null) stringResource(R.string.common_uninstall) else delete,
|
||||
onConfirm = { a.onAddonDelete(target, name) },
|
||||
onConfirm = { asking = false; if (progresses[name] == null) a.onAddonDelete(target, name) },
|
||||
onDismiss = { asking = false },
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun updateAddon(
|
||||
context: android.content.Context, name: String, update: WowAddonCatalog.Addon?, target: WowAddons.Target,
|
||||
curse: Pair<CurseForgeApp.Project, CurseLink>?, onProgress: (Int) -> Unit,
|
||||
): Pair<String?, Boolean> = withContext(Dispatchers.IO) {
|
||||
if (curse != null) {
|
||||
val (project, link) = curse
|
||||
val done = runCatching { link.change(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
||||
WowAddons.changed()
|
||||
(if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)) to done
|
||||
} else update?.let { installAddon(context, it, target, onProgress).let { (message, version) -> message to (version != null) } } ?: (null to false)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CloudRows(g: Library.SteamGame, onSynced: () -> Unit = {}) {
|
||||
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return
|
||||
|
||||
@@ -15,6 +15,7 @@ import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.frontend.SteamHidden
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
|
||||
internal const val LIBRARY_HIDDEN = "hidden"
|
||||
internal val HIDDEN_DOT = androidx.compose.ui.graphics.Color(0xFF9AA0A6)
|
||||
@@ -46,14 +47,18 @@ internal object LibraryHidden {
|
||||
}
|
||||
}
|
||||
|
||||
fun steamId(game: Library.SteamGame?): Long? = game?.takeIf { Library.fromSteamClient(it) }?.appId?.toLong()
|
||||
/** The Steam client's own id for a game it lists, or for an owned Steam game it has not installed ([key] `steamstore:<appid>`). */
|
||||
fun steamId(game: Library.SteamGame?, key: String = ""): Long? =
|
||||
game?.takeIf { Library.fromSteamClient(it) }?.appId?.toLong()
|
||||
?: key.takeIf { game == null && it.startsWith("${Store.STEAM.id}:") }?.substringAfter(':')?.toLongOrNull()
|
||||
|
||||
fun isHidden(key: String, game: Library.SteamGame?): Boolean = key in keys || steamId(game)?.let { it in steam } == true
|
||||
fun isHidden(key: String, game: Library.SteamGame?): Boolean = key in keys || steamId(game, key)?.let { it in steam } == true
|
||||
|
||||
fun isHidden(entry: LibraryEntry): Boolean = isHidden(entry.favoriteKey, entry.game)
|
||||
fun isHidden(entry: LibraryEntry): Boolean =
|
||||
isHidden(entry.favoriteKey, entry.game) || entry.item?.takeIf { it.store == Store.STEAM }?.let { it.key in keys || it.id.toLongOrNull()?.let { id -> id in steam } == true } == true
|
||||
|
||||
fun set(context: Context, key: String, game: Library.SteamGame?, hidden: Boolean): Boolean {
|
||||
val id = steamId(game)
|
||||
val id = steamId(game, key)
|
||||
val root = SessionPrefs.activeSteamRoot(context)
|
||||
val written = id?.let { SteamHidden.write(root, it, hidden) }
|
||||
if (id != null) {
|
||||
|
||||
@@ -139,7 +139,8 @@ internal class LibraryEntry(
|
||||
val game: Library.SteamGame?, val item: CatalogItem?, val installed: Boolean,
|
||||
) {
|
||||
val storeKey: String? get() = item?.key ?: game?.storeId?.let { "${game.source}:$it" }
|
||||
val favoriteKey: String get() = storeKey ?: key
|
||||
/** A Steam game keeps the key it has once the Steam client lists it, so favoriting it before the install carries over. */
|
||||
val favoriteKey: String get() = if (item?.store == Store.STEAM) "app:${item.id}" else storeKey ?: key
|
||||
}
|
||||
|
||||
internal fun libraryEntries(
|
||||
@@ -149,6 +150,7 @@ internal fun libraryEntries(
|
||||
val out = ArrayList<LibraryEntry>()
|
||||
for (g in games.sortedBy { it.library == Library.XBOX_CLOUD }) {
|
||||
if (g.library == Library.EPIC_LAUNCHER) continue
|
||||
if (Library.fromSteamClient(g)) claimed.add("${Store.STEAM.id}:${g.appId}")
|
||||
val storeKey = g.storeId?.let { "${g.source}:$it" }
|
||||
val item = storeKey?.let { k -> Store.byId(g.source)?.let { st -> owned[st]?.firstOrNull { it.key == k } } }
|
||||
if (storeKey != null) {
|
||||
@@ -160,7 +162,7 @@ internal fun libraryEntries(
|
||||
}
|
||||
for (store in Store.entries) for (item in owned[store].orEmpty()) {
|
||||
if (!claimed.add(item.key)) continue
|
||||
out += LibraryEntry(GameRef.key(item), store.id, item.title, null, item, installed = item.key in installedStore)
|
||||
out += LibraryEntry(GameRef.key(item), store.librarySource, item.title, null, item, installed = item.key in installedStore)
|
||||
}
|
||||
return out.distinctBy { it.key }
|
||||
}
|
||||
@@ -297,7 +299,7 @@ internal object LibraryView {
|
||||
fun showOwned(context: android.content.Context, store: Store) {
|
||||
SessionPrefs.setLibraryShowUninstalled(context, true)
|
||||
ownedRequest++
|
||||
source = store.id
|
||||
source = store.librarySource
|
||||
query = ""
|
||||
focusFirst = true
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ internal object StoreTabsState {
|
||||
private set
|
||||
|
||||
fun load(context: android.content.Context) {
|
||||
SessionPrefs.settleStoresTabOrder(context, Store.entries.map { it.id })
|
||||
SessionPrefs.settleStoresTabOrder(context, Store.tabbed.map { it.id })
|
||||
tabs = arrangeStoreTabs(SessionPrefs.storesTabOrder(context), SessionPrefs.storesTabHidden(context))
|
||||
libraryPlaces = SessionPrefs.libraryTabPlaces(context) ?: DEFAULT_LIBRARY_PLACES
|
||||
libraryHidden = SessionPrefs.libraryTabsHidden(context) + listOfNotNull(LIBRARY_HIDDEN.takeUnless { SessionPrefs.libraryShowHidden(context) })
|
||||
|
||||
@@ -93,6 +93,7 @@ class ModeSettings(
|
||||
val steamClientArch: String? = null,
|
||||
val returnAfterGame: Boolean? = null,
|
||||
val shaderPrecache: Boolean? = null,
|
||||
val valveProtonOnDemand: Boolean? = null,
|
||||
val steamRepairQueued: Boolean = false,
|
||||
val mangoapp: Boolean = true,
|
||||
val steamController: String? = null,
|
||||
@@ -158,6 +159,7 @@ class ModeSettingsActions(
|
||||
val onMangoapp: (Boolean) -> Unit = {},
|
||||
val onReturnAfterGame: (Boolean) -> Unit = {},
|
||||
val onShaderPrecache: (Boolean) -> Unit = {},
|
||||
val onValveProtonOnDemand: (Boolean) -> Unit = {},
|
||||
val onSteamController: (String) -> Unit = {},
|
||||
val onUnfoldedControls: (Boolean) -> Unit = {},
|
||||
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
|
||||
@@ -534,6 +536,10 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
stringResource(R.string.mode_shader_precache_hint),
|
||||
s.shaderPrecache, onChange = a.onShaderPrecache,
|
||||
)
|
||||
if (s.valveProtonOnDemand != null) ToggleRow(
|
||||
host, "valveprotonondemand", stringResource(R.string.mode_valve_proton_on_demand), null,
|
||||
s.valveProtonOnDemand, onChange = a.onValveProtonOnDemand,
|
||||
)
|
||||
SettingsRow(
|
||||
stringResource(R.string.mode_steam_repair),
|
||||
stringResource(if (s.steamRepairQueued) R.string.mode_steam_repair_queued else R.string.mode_steam_repair_hint),
|
||||
|
||||
@@ -27,9 +27,9 @@ internal object DeveloperTools {
|
||||
internal object NavTabs {
|
||||
const val MORE = "more"
|
||||
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "agent")
|
||||
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
|
||||
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "agent")
|
||||
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
|
||||
private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync")
|
||||
private const val LAYOUT_VERSION = 2
|
||||
@@ -95,6 +95,15 @@ internal object NavTabs {
|
||||
else -> true
|
||||
}
|
||||
|
||||
// Apps only has content when DroidDeck is the home app, so it follows that state on each change and
|
||||
// otherwise stays wherever the user put it.
|
||||
fun syncHomeApps(context: Context, homeSelected: Boolean) {
|
||||
val seen = SessionPrefs.appsTabHomeSeen(context)
|
||||
SessionPrefs.setAppsTabHomeSeen(context, homeSelected)
|
||||
if (seen == homeSelected || (seen == null && !homeSelected)) return
|
||||
setHidden(context, "android-apps", !homeSelected)
|
||||
}
|
||||
|
||||
fun hideable(key: String) = key != "setup"
|
||||
|
||||
fun place(s: FrontEndState, key: String): TabPlace = when {
|
||||
|
||||
@@ -115,10 +115,11 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
account = { host ->
|
||||
SettingsGroup(stringResource(R.string.setup_account)) {
|
||||
ToggleRow(
|
||||
host, "offline", stringResource(R.string.setup_offline),
|
||||
host, "offline-auto", stringResource(R.string.setup_offline_auto),
|
||||
s.offlineAccount?.let { if (it.isEmpty()) stringResource(R.string.setup_signed_in_unnamed) else stringResource(R.string.setup_signed_in, it) } ?: stringResource(R.string.setup_sign_in_first),
|
||||
s.offline, enabled = s.offlineAccount != null,
|
||||
) { a.onOffline() }
|
||||
s.offlineAuto, enabled = s.offlineAccount != null,
|
||||
) { a.onOfflineAuto() }
|
||||
if (!s.offlineAuto) ToggleRow(host, "offline", stringResource(R.string.setup_offline), null, s.offline, enabled = s.offlineAccount != null) { a.onOffline() }
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
@@ -39,7 +39,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
|
||||
Store.UBISOFT.id -> SourceColours(Color(0xFF0B1E44), Color(0xFFA8C6FF), Color(0xFF2E7DFF))
|
||||
Store.EA.id -> SourceColours(Color(0xFF3A0E12), Color(0xFFFF9A9A), Color(0xFFFF4747))
|
||||
Store.ROCKSTAR.id -> SourceColours(Color(0xFF3A2A06), Color(0xFFFFD780), Color(0xFFFCAF17))
|
||||
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
|
||||
Library.SOURCE_STEAM, Store.STEAM.id -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
|
||||
Library.SOURCE_COLLECTION -> SourceColours(Color(0xFF2B1A3D), Color(0xFFD2A8FF), Color(0xFFA25BFF))
|
||||
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
|
||||
else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF))
|
||||
@@ -47,7 +47,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
|
||||
|
||||
@Composable
|
||||
internal fun sourceLabel(source: String): String = when (source) {
|
||||
Library.SOURCE_STEAM -> stringResource(R.string.source_steam)
|
||||
Library.SOURCE_STEAM, Store.STEAM.id -> stringResource(R.string.source_steam)
|
||||
Library.SOURCE_COLLECTION -> stringResource(R.string.soundtracks_collections)
|
||||
Store.GOG.id -> Store.GOG.label
|
||||
Store.EPIC.id -> Store.EPIC.label
|
||||
|
||||
@@ -27,6 +27,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -46,7 +47,10 @@ import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.StoreSizes
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.steam.SteamClient
|
||||
import com.droiddeck.launcher.stores.steam.SteamStore
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.gog.GogDownloadManager
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -133,6 +137,61 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SteamInstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
val targets by produceState<List<SteamClient.Target>?>(null, item.key) {
|
||||
value = withContext(Dispatchers.IO) { runCatching { SteamClient.targets(ctx) }.getOrDefault(emptyList()) }
|
||||
}
|
||||
val needed by produceState(StoreSizes.size(item), item.key) {
|
||||
val bytes = withContext(Dispatchers.IO) { runCatching { SteamStore.plannedBytes(ctx, item) }.getOrDefault(0L) }
|
||||
if (bytes > 0L) value = bytes
|
||||
}
|
||||
val list = targets
|
||||
val focus = remember(list?.size) { List(list?.size ?: 0) { FocusRequester() } }
|
||||
LaunchedEffect(focus) { if (focus.isNotEmpty()) focusWithinFrames({ false }) { focus[0] } }
|
||||
AppDialog(shown, close, "steamInstallWhere", wide = false, maxWidth = 440.dp) {
|
||||
Rise(0) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
stringResource(R.string.stores_install_title, item.title), fontSize = 15.sp, color = colors.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.common_cancel), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(Shape12).focusGlide().clickable(role = Role.Button, onClick = close).controllerConfirm(onClick = close).padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Rise(1) {
|
||||
when {
|
||||
list == null -> androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
|
||||
list.isEmpty() -> Note(stringResource(R.string.game_sync_err_steam_library))
|
||||
else -> Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
list.forEachIndexed { i, t ->
|
||||
val isLow = StoreInstallRoot.insufficientSpace(needed, t.freeBytes)
|
||||
val freeText = when {
|
||||
t.freeBytes < 0L -> stringResource(R.string.stores_target_free_unknown)
|
||||
isLow -> stringResource(R.string.stores_storage_low, formatBytes(t.freeBytes), formatBytes(needed))
|
||||
else -> stringResource(R.string.stores_target_free, formatBytes(t.freeBytes))
|
||||
}
|
||||
TargetRow(
|
||||
label = t.label, free = freeText, removable = t.removable, folder = t.folder, focus = focus[i],
|
||||
modifier = Modifier.fillMaxWidth(), warning = isLow,
|
||||
) {
|
||||
SteamStore.install(ctx, item, t)
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TargetRow(label: String, free: String, removable: Boolean, folder: Boolean, focus: FocusRequester, modifier: Modifier, warning: Boolean = false, onPick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
|
||||
@@ -1031,6 +1031,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
|
||||
Store.UBISOFT -> Color(0xFF2E7DFF) to Color(0xFF1A5BD6)
|
||||
Store.EA -> Color(0xFFFF4747) to Color(0xFFE03030)
|
||||
Store.ROCKSTAR -> Color(0xFFFCAF17) to Color(0xFFD98E00)
|
||||
Store.STEAM -> Color(0xFF1A9FFF) to Color(0xFF0F6FC0)
|
||||
null -> return base
|
||||
}
|
||||
val on = if (accent.luminance() > 0.18f) Color(0xFF0B0B0D) else Color.White
|
||||
@@ -1323,6 +1324,6 @@ internal fun openUrl(ctx: android.content.Context, url: String) {
|
||||
}
|
||||
|
||||
internal fun launchStoreGame(store: Store, id: String, s: FrontEndState, a: FrontEndActions) {
|
||||
val game = s.steamGames.firstOrNull { it.source == store.id && it.storeId == id }
|
||||
val game = GameRef(null, store, id).game(s.steamGames)
|
||||
if (game != null) a.onSteamGame(game) else a.onStoreGame(store, id)
|
||||
}
|
||||
@@ -934,6 +934,7 @@
|
||||
<string name="setup_reset_settings_session_running">أوقف الجلسة قبل إعادة تعيين الإعدادات.</string>
|
||||
<string name="setup_reset_settings_partial">أُعيد تعيين الإعدادات، لكن ليس كلها. التفاصيل في السجلات.</string>
|
||||
<string name="setup_offline">وضع عدم الاتصال</string>
|
||||
<string name="setup_offline_auto">وضع عدم الاتصال التلقائي</string>
|
||||
<string name="setup_sign_in_first">سجّل الدخول إلى Steam أولًا</string>
|
||||
<string name="setup_launcher">المشغّل</string>
|
||||
<string name="setup_language">اللغة</string>
|
||||
@@ -4240,4 +4241,7 @@
|
||||
<string name="theme_custom_error">خطأ</string>
|
||||
<string name="hud_only_during_game">عرض HUD أثناء اللعب فقط</string>
|
||||
<string name="hud_only_during_game_hint">إخفاء HUD عند عدم اكتشاف إطارات اللعبة.</string>
|
||||
<string name="steam_store_close_steam">أغلق Steam أولاً</string>
|
||||
<string name="steam_store_session_wait">أوقف تنزيل Steam مؤقتًا أولاً</string>
|
||||
<string name="steam_store_linux_build">تثبّت هذه اللعبة إصدار Linux الخاص بها. ثبّتها من Steam.</string>
|
||||
</resources>
|
||||
@@ -952,6 +952,7 @@
|
||||
<string name="setup_reset_settings_session_running">Detén la sesión antes de restablecer los ajustes.</string>
|
||||
<string name="setup_reset_settings_partial">Los ajustes se restablecieron, pero algunas partes no se pudieron restablecer. Los registros tienen los detalles.</string>
|
||||
<string name="setup_offline">Modo sin conexión</string>
|
||||
<string name="setup_offline_auto">Modo sin conexión automático</string>
|
||||
<string name="setup_sign_in_first">Inicia sesión en Steam primero</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
<string name="setup_language">Idioma</string>
|
||||
@@ -4120,4 +4121,7 @@
|
||||
<string name="theme_custom_error">Error</string>
|
||||
<string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string>
|
||||
<string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string>
|
||||
<string name="steam_store_close_steam">Cierra Steam primero</string>
|
||||
<string name="steam_store_session_wait">Pausa primero la descarga de Steam</string>
|
||||
<string name="steam_store_linux_build">Este juego instala su versión para Linux. Instálalo desde Steam.</string>
|
||||
</resources>
|
||||
@@ -922,6 +922,7 @@
|
||||
<string name="setup_reset_settings_session_running">Спри сесията, преди да нулираш настройките.</string>
|
||||
<string name="setup_reset_settings_partial">Настройките са нулирани, но не всички. Подробностите са в логовете.</string>
|
||||
<string name="setup_offline">Офлайн режим</string>
|
||||
<string name="setup_offline_auto">Автоматичен офлайн режим</string>
|
||||
<string name="setup_sign_in_first">Първо влезте в Steam</string>
|
||||
<string name="setup_launcher">Лаунчър</string>
|
||||
<string name="setup_language">Език</string>
|
||||
@@ -4080,4 +4081,7 @@
|
||||
<string name="theme_custom_error">Грешка</string>
|
||||
<string name="hud_only_during_game">Показвай HUD само по време на игра</string>
|
||||
<string name="hud_only_during_game_hint">Скривай HUD, когато не се засичат кадри от играта.</string>
|
||||
<string name="steam_store_close_steam">Първо затворете Steam</string>
|
||||
<string name="steam_store_session_wait">Първо поставете на пауза изтеглянето от Steam</string>
|
||||
<string name="steam_store_linux_build">Тази игра инсталира версията си за Linux. Инсталирайте я от Steam.</string>
|
||||
</resources>
|
||||
@@ -928,6 +928,7 @@
|
||||
<string name="setup_reset_settings_session_running">Před obnovením nastavení zastav relaci.</string>
|
||||
<string name="setup_reset_settings_partial">Nastavení byla obnovena, ale ne všechna. Podrobnosti jsou v logech.</string>
|
||||
<string name="setup_offline">Režim offline</string>
|
||||
<string name="setup_offline_auto">Automatický režim offline</string>
|
||||
<string name="setup_sign_in_first">Nejprve se přihlaste ke Steamu</string>
|
||||
<string name="setup_launcher">Spouštěč</string>
|
||||
<string name="setup_language">Jazyk</string>
|
||||
@@ -4160,4 +4161,7 @@
|
||||
<string name="theme_custom_error">Chyba</string>
|
||||
<string name="hud_only_during_game">Zobrazovat HUD pouze během hry</string>
|
||||
<string name="hud_only_during_game_hint">Skrýt HUD, když nejsou detekovány snímky hry.</string>
|
||||
<string name="steam_store_close_steam">Nejprve zavřete Steam</string>
|
||||
<string name="steam_store_session_wait">Nejprve pozastavte stahování ze Steamu</string>
|
||||
<string name="steam_store_linux_build">Tato hra instaluje svou verzi pro Linux. Nainstalujte ji ze Steamu.</string>
|
||||
</resources>
|
||||
@@ -922,6 +922,7 @@
|
||||
<string name="setup_reset_settings_session_running">Stop sessionen, før du nulstiller indstillinger.</string>
|
||||
<string name="setup_reset_settings_partial">Indstillingerne blev nulstillet, men ikke alle. Detaljerne står i loggen.</string>
|
||||
<string name="setup_offline">Offlinetilstand</string>
|
||||
<string name="setup_offline_auto">Automatisk offlinetilstand</string>
|
||||
<string name="setup_sign_in_first">Log ind på Steam først</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
<string name="setup_language">Sprog</string>
|
||||
@@ -4080,4 +4081,7 @@
|
||||
<string name="theme_custom_error">Fejl</string>
|
||||
<string name="hud_only_during_game">Vis kun HUD under spil</string>
|
||||
<string name="hud_only_during_game_hint">Skjul HUD, når der ikke registreres spilbilleder.</string>
|
||||
<string name="steam_store_close_steam">Luk Steam først</string>
|
||||
<string name="steam_store_session_wait">Sæt Steam-downloaden på pause først</string>
|
||||
<string name="steam_store_linux_build">Dette spil installerer sin Linux-version. Installer det fra Steam.</string>
|
||||
</resources>
|
||||
@@ -914,6 +914,7 @@
|
||||
<string name="setup_log_export_failed">Sitzungsprotokolle konnten nicht gespeichert werden.</string>
|
||||
<string name="setup_log_delete_failed">Sitzungsprotokolle konnten nicht gelöscht werden.</string>
|
||||
<string name="setup_offline">Offlinemodus</string>
|
||||
<string name="setup_offline_auto">Automatischer Offlinemodus</string>
|
||||
<string name="setup_sign_in_first">Melde dich zuerst bei Steam an</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
<string name="setup_language">Sprache</string>
|
||||
@@ -4080,4 +4081,7 @@
|
||||
<string name="theme_custom_error">Fehler</string>
|
||||
<string name="hud_only_during_game">HUD nur während eines Spiels anzeigen</string>
|
||||
<string name="hud_only_during_game_hint">HUD ausblenden, wenn keine Spielframes erkannt werden.</string>
|
||||
<string name="steam_store_close_steam">Schließe zuerst Steam</string>
|
||||
<string name="steam_store_session_wait">Pausiere zuerst den Steam-Download</string>
|
||||
<string name="steam_store_linux_build">Dieses Spiel installiert seine Linux-Version. Installiere es über Steam.</string>
|
||||
</resources>
|
||||
@@ -922,6 +922,7 @@
|
||||
<string name="setup_reset_settings_session_running">Σταμάτησε τη συνεδρία πριν κάνεις επαναφορά ρυθμίσεων.</string>
|
||||
<string name="setup_reset_settings_partial">Οι ρυθμίσεις επαναφέρθηκαν, αλλά όχι όλες. Οι λεπτομέρειες είναι στα αρχεία καταγραφής.</string>
|
||||
<string name="setup_offline">Λειτουργία εκτός σύνδεσης</string>
|
||||
<string name="setup_offline_auto">Αυτόματη λειτουργία εκτός σύνδεσης</string>
|
||||
<string name="setup_sign_in_first">Συνδεθείτε πρώτα στο Steam</string>
|
||||
<string name="setup_launcher">Εκκινητής</string>
|
||||
<string name="setup_language">Γλώσσα</string>
|
||||
@@ -4080,4 +4081,7 @@
|
||||
<string name="theme_custom_error">Σφάλμα</string>
|
||||
<string name="hud_only_during_game">Εμφάνιση HUD μόνο κατά τη διάρκεια παιχνιδιού</string>
|
||||
<string name="hud_only_during_game_hint">Απόκρυψη HUD όταν δεν ανιχνεύονται καρέ παιχνιδιού.</string>
|
||||
<string name="steam_store_close_steam">Κλείστε πρώτα το Steam</string>
|
||||
<string name="steam_store_session_wait">Θέστε πρώτα σε παύση τη λήψη του Steam</string>
|
||||
<string name="steam_store_linux_build">Αυτό το παιχνίδι εγκαθιστά την έκδοσή του για Linux. Εγκαταστήστε το από το Steam.</string>
|
||||
</resources>
|
||||
@@ -925,6 +925,7 @@
|
||||
<string name="setup_reset_settings_session_running">Detén la sesión antes de restablecer los ajustes.</string>
|
||||
<string name="setup_reset_settings_partial">Los ajustes se restablecieron, pero algunas partes no se pudieron restablecer. Los registros tienen los detalles.</string>
|
||||
<string name="setup_offline">Modo sin conexión</string>
|
||||
<string name="setup_offline_auto">Modo sin conexión automático</string>
|
||||
<string name="setup_sign_in_first">Inicia sesión en Steam primero</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
<string name="setup_language">Idioma</string>
|
||||
@@ -4120,4 +4121,7 @@
|
||||
<string name="theme_custom_error">Error</string>
|
||||
<string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string>
|
||||
<string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string>
|
||||
<string name="steam_store_close_steam">Cierra Steam primero</string>
|
||||
<string name="steam_store_session_wait">Pausa primero la descarga de Steam</string>
|
||||
<string name="steam_store_linux_build">Este juego instala su versión para Linux. Instálalo desde Steam.</string>
|
||||
</resources>
|
||||
@@ -922,6 +922,7 @@
|
||||
<string name="setup_reset_settings_session_running">Pysäytä istunto ennen asetusten palauttamista.</string>
|
||||
<string name="setup_reset_settings_partial">Asetukset palautettiin, mutta ei kaikkia. Tiedot ovat lokeissa.</string>
|
||||
<string name="setup_offline">Offline-tila</string>
|
||||
<string name="setup_offline_auto">Automaattinen offline-tila</string>
|
||||
<string name="setup_sign_in_first">Kirjaudu Steamiin ensin</string>
|
||||
<string name="setup_launcher">Käynnistin</string>
|
||||
<string name="setup_language">Kieli</string>
|
||||
@@ -4080,4 +4081,7 @@
|
||||
<string name="theme_custom_error">Virhe</string>
|
||||
<string name="hud_only_during_game">Näytä HUD vain pelin aikana</string>
|
||||
<string name="hud_only_during_game_hint">Piilota HUD, kun pelin ruutuja ei havaita.</string>
|
||||
<string name="steam_store_close_steam">Sulje Steam ensin</string>
|
||||
<string name="steam_store_session_wait">Keskeytä Steam-lataus ensin</string>
|
||||
<string name="steam_store_linux_build">Tämä peli asentaa Linux-versionsa. Asenna se Steamista.</string>
|
||||
</resources>
|
||||
@@ -925,6 +925,7 @@
|
||||
<string name="setup_reset_settings_session_running">Arrêtez la session avant de réinitialiser les paramètres.</string>
|
||||
<string name="setup_reset_settings_partial">Les paramètres ont été réinitialisés, mais certaines parties n\'ont pas pu l\'être. Les journaux contiennent les détails.</string>
|
||||
<string name="setup_offline">Mode hors ligne</string>
|
||||
<string name="setup_offline_auto">Mode hors ligne automatique</string>
|
||||
<string name="setup_sign_in_first">Veuillez d\'abord vous connecter à Steam</string>
|
||||
<string name="setup_launcher">Lanceur</string>
|
||||
<string name="setup_language">Langue</string>
|
||||
@@ -4119,4 +4120,7 @@
|
||||
<string name="theme_custom_error">Erreur</string>
|
||||
<string name="hud_only_during_game">Afficher le HUD uniquement pendant une partie</string>
|
||||
<string name="hud_only_during_game_hint">Masquer le HUD lorsqu’aucune image du jeu n’est détectée.</string>
|
||||
<string name="steam_store_close_steam">Fermez d\'abord Steam</string>
|
||||
<string name="steam_store_session_wait">Mettez d\'abord en pause le téléchargement Steam</string>
|
||||
<string name="steam_store_linux_build">Ce jeu installe sa version Linux. Installez-le depuis Steam.</string>
|
||||
</resources>
|
||||
@@ -922,6 +922,7 @@
|
||||
<string name="setup_reset_settings_session_running">सेटिंग रीसेट करने से पहले सेशन रोकें।</string>
|
||||
<string name="setup_reset_settings_partial">सेटिंग रीसेट हुईं, पर सभी नहीं। विवरण लॉग में हैं।</string>
|
||||
<string name="setup_offline">ऑफ़लाइन मोड</string>
|
||||
<string name="setup_offline_auto">स्वचालित ऑफ़लाइन मोड</string>
|
||||
<string name="setup_sign_in_first">पहले Steam में साइन इन करें</string>
|
||||
<string name="setup_launcher">लॉन्चर</string>
|
||||
<string name="setup_language">भाषा</string>
|
||||
@@ -4080,4 +4081,7 @@
|
||||
<string name="theme_custom_error">त्रुटि</string>
|
||||
<string name="hud_only_during_game">HUD केवल गेम के दौरान दिखाएँ</string>
|
||||
<string name="hud_only_during_game_hint">गेम के फ़्रेम का पता न चलने पर HUD छिपाएँ।</string>
|
||||
<string name="steam_store_close_steam">पहले Steam बंद करें</string>
|
||||
<string name="steam_store_session_wait">पहले Steam डाउनलोड रोकें</string>
|
||||
<string name="steam_store_linux_build">यह गेम अपना Linux संस्करण इंस्टॉल करता है। इसे Steam से इंस्टॉल करें।</string>
|
||||
</resources>
|
||||
@@ -922,6 +922,7 @@
|
||||
<string name="setup_reset_settings_session_running">A beállítások visszaállítása előtt állítsd le a munkamenetet.</string>
|
||||
<string name="setup_reset_settings_partial">A beállítások visszaálltak, de nem mindegyik. A részletek a naplókban vannak.</string>
|
||||
<string name="setup_offline">Offline mód</string>
|
||||
<string name="setup_offline_auto">Automatikus offline mód</string>
|
||||
<string name="setup_sign_in_first">Előbb jelentkezzen be a Steambe</string>
|
||||
<string name="setup_launcher">Indítóalkalmazás</string>
|
||||
<string name="setup_language">Nyelv</string>
|
||||
@@ -4080,4 +4081,7 @@
|
||||
<string name="theme_custom_error">Hiba</string>
|
||||
<string name="hud_only_during_game">HUD megjelenítése csak játék közben</string>
|
||||
<string name="hud_only_during_game_hint">HUD elrejtése, ha nem észlelhetők játék képkockái.</string>
|
||||
<string name="steam_store_close_steam">Előbb zárd be a Steamet</string>
|
||||
<string name="steam_store_session_wait">Előbb szüneteltesd a Steam-letöltést</string>
|
||||
<string name="steam_store_linux_build">Ez a játék a Linux-verzióját telepíti. Telepítsd a Steamből.</string>
|
||||
</resources>
|
||||
@@ -919,6 +919,7 @@
|
||||
<string name="setup_reset_settings_session_running">Hentikan sesi sebelum menyetel ulang setelan.</string>
|
||||
<string name="setup_reset_settings_partial">Setelan disetel ulang, tetapi tidak semuanya. Rinciannya ada di log.</string>
|
||||
<string name="setup_offline">Mode luring</string>
|
||||
<string name="setup_offline_auto">Mode luring otomatis</string>
|
||||
<string name="setup_sign_in_first">Masuk ke Steam terlebih dahulu</string>
|
||||
<string name="setup_launcher">Peluncur</string>
|
||||
<string name="setup_language">Bahasa</string>
|
||||
@@ -4050,4 +4051,7 @@
|
||||
<string name="theme_custom_error">Kesalahan</string>
|
||||
<string name="hud_only_during_game">Tampilkan HUD hanya saat bermain</string>
|
||||
<string name="hud_only_during_game_hint">Sembunyikan HUD saat tidak ada frame game yang terdeteksi.</string>
|
||||
<string name="steam_store_close_steam">Tutup Steam terlebih dahulu</string>
|
||||
<string name="steam_store_session_wait">Jeda unduhan Steam terlebih dahulu</string>
|
||||
<string name="steam_store_linux_build">Game ini memasang versi Linux-nya. Pasang dari Steam.</string>
|
||||
</resources>
|
||||
@@ -917,6 +917,7 @@
|
||||
<string name="setup_log_export_failed">Impossibile salvare i log di sessione.</string>
|
||||
<string name="setup_log_delete_failed">Impossibile eliminare i log di sessione.</string>
|
||||
<string name="setup_offline">Modalità offline</string>
|
||||
<string name="setup_offline_auto">Modalità offline automatica</string>
|
||||
<string name="setup_sign_in_first">Accedi prima a Steam</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
<string name="setup_language">Lingua</string>
|
||||
@@ -4119,4 +4120,7 @@
|
||||
<string name="theme_custom_error">Errore</string>
|
||||
<string name="hud_only_during_game">Mostra l’HUD solo durante il gioco</string>
|
||||
<string name="hud_only_during_game_hint">Nascondi l’HUD quando non vengono rilevati fotogrammi del gioco.</string>
|
||||
<string name="steam_store_close_steam">Chiudi prima Steam</string>
|
||||
<string name="steam_store_session_wait">Metti prima in pausa il download di Steam</string>
|
||||
<string name="steam_store_linux_build">Questo gioco installa la sua versione Linux. Installalo da Steam.</string>
|
||||
</resources>
|
||||
@@ -919,6 +919,7 @@
|
||||
<string name="setup_reset_settings_session_running">設定をリセットする前にセッションを停止してください。</string>
|
||||
<string name="setup_reset_settings_partial">設定はリセットされましたが、一部をリセットできませんでした。詳細はログを確認してください。</string>
|
||||
<string name="setup_offline">オフラインモード</string>
|
||||
<string name="setup_offline_auto">自動オフラインモード</string>
|
||||
<string name="setup_sign_in_first">先にSteamにログインしてください</string>
|
||||
<string name="setup_launcher">ランチャー</string>
|
||||
<string name="setup_language">言語</string>
|
||||
@@ -4050,4 +4051,7 @@
|
||||
<string name="theme_custom_error">エラー</string>
|
||||
<string name="hud_only_during_game">ゲーム中のみHUDを表示</string>
|
||||
<string name="hud_only_during_game_hint">ゲームのフレームが検出されないときはHUDを非表示にする。</string>
|
||||
<string name="steam_store_close_steam">先に Steam を閉じてください</string>
|
||||
<string name="steam_store_session_wait">先に Steam のダウンロードを一時停止してください</string>
|
||||
<string name="steam_store_linux_build">このゲームは Linux 版をインストールします。Steam からインストールしてください。</string>
|
||||
</resources>
|
||||
@@ -919,6 +919,7 @@
|
||||
<string name="setup_reset_settings_session_running">설정을 초기화하기 전에 세션을 중지하세요.</string>
|
||||
<string name="setup_reset_settings_partial">설정이 초기화되었지만 일부는 초기화하지 못했습니다. 자세한 내용은 로그를 확인하세요.</string>
|
||||
<string name="setup_offline">오프라인 모드</string>
|
||||
<string name="setup_offline_auto">자동 오프라인 모드</string>
|
||||
<string name="setup_sign_in_first">먼저 Steam에 로그인하세요</string>
|
||||
<string name="setup_launcher">런처</string>
|
||||
<string name="setup_language">언어</string>
|
||||
@@ -4050,4 +4051,7 @@
|
||||
<string name="theme_custom_error">오류</string>
|
||||
<string name="hud_only_during_game">게임 중에만 HUD 표시</string>
|
||||
<string name="hud_only_during_game_hint">게임 프레임이 감지되지 않으면 HUD 숨기기.</string>
|
||||
<string name="steam_store_close_steam">먼저 Steam을 닫으세요</string>
|
||||
<string name="steam_store_session_wait">먼저 Steam 다운로드를 일시 중지하세요</string>
|
||||
<string name="steam_store_linux_build">이 게임은 Linux 버전을 설치합니다. Steam에서 설치하세요.</string>
|
||||
</resources>
|
||||
@@ -919,6 +919,7 @@
|
||||
<string name="setup_reset_settings_session_running">Hentikan sesi sebelum menetap semula tetapan.</string>
|
||||
<string name="setup_reset_settings_partial">Tetapan telah ditetap semula, tetapi bukan semuanya. Butirannya ada dalam log.</string>
|
||||
<string name="setup_offline">Mod luar talian</string>
|
||||
<string name="setup_offline_auto">Mod luar talian automatik</string>
|
||||
<string name="setup_sign_in_first">Log masuk ke Steam dahulu</string>
|
||||
<string name="setup_launcher">Pelancar</string>
|
||||
<string name="setup_language">Bahasa</string>
|
||||
@@ -4050,4 +4051,7 @@
|
||||
<string name="theme_custom_error">Ralat</string>
|
||||
<string name="hud_only_during_game">Paparkan HUD hanya semasa bermain</string>
|
||||
<string name="hud_only_during_game_hint">Sembunyikan HUD apabila bingkai permainan tidak dikesan.</string>
|
||||
<string name="steam_store_close_steam">Tutup Steam dahulu</string>
|
||||
<string name="steam_store_session_wait">Jeda muat turun Steam dahulu</string>
|
||||
<string name="steam_store_linux_build">Permainan ini memasang versi Linuxnya. Pasang daripada Steam.</string>
|
||||
</resources>
|
||||
@@ -922,6 +922,7 @@
|
||||
<string name="setup_reset_settings_session_running">Stopp økten før du tilbakestiller innstillinger.</string>
|
||||
<string name="setup_reset_settings_partial">Innstillingene ble tilbakestilt, men ikke alle. Detaljene står i loggen.</string>
|
||||
<string name="setup_offline">Frakoblet modus</string>
|
||||
<string name="setup_offline_auto">Automatisk frakoblet modus</string>
|
||||
<string name="setup_sign_in_first">Logg inn på Steam først</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
<string name="setup_language">Språk</string>
|
||||
@@ -4080,4 +4081,7 @@
|
||||
<string name="theme_custom_error">Feil</string>
|
||||
<string name="hud_only_during_game">Vis HUD bare mens du spiller</string>
|
||||
<string name="hud_only_during_game_hint">Skjul HUD når ingen spillbilder registreres.</string>
|
||||
<string name="steam_store_close_steam">Lukk Steam først</string>
|
||||
<string name="steam_store_session_wait">Sett Steam-nedlastingen på pause først</string>
|
||||
<string name="steam_store_linux_build">Dette spillet installerer Linux-versjonen sin. Installer det fra Steam.</string>
|
||||
</resources>
|
||||
@@ -922,6 +922,7 @@
|
||||
<string name="setup_reset_settings_session_running">Stop de sessie voordat je instellingen reset.</string>
|
||||
<string name="setup_reset_settings_partial">De instellingen zijn gereset, maar niet alles. De details staan in de logs.</string>
|
||||
<string name="setup_offline">Offlinemodus</string>
|
||||
<string name="setup_offline_auto">Automatische offlinemodus</string>
|
||||
<string name="setup_sign_in_first">Meld je eerst aan bij Steam</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
<string name="setup_language">Taal</string>
|
||||
@@ -4080,4 +4081,7 @@
|
||||
<string name="theme_custom_error">Fout</string>
|
||||
<string name="hud_only_during_game">HUD alleen tijdens een game weergeven</string>
|
||||
<string name="hud_only_during_game_hint">Verberg de HUD wanneer er geen gameframes worden gedetecteerd.</string>
|
||||
<string name="steam_store_close_steam">Sluit eerst Steam</string>
|
||||
<string name="steam_store_session_wait">Pauzeer eerst de Steam-download</string>
|
||||
<string name="steam_store_linux_build">Deze game installeert zijn Linux-versie. Installeer hem via Steam.</string>
|
||||
</resources>
|
||||
@@ -928,6 +928,7 @@
|
||||
<string name="setup_reset_settings_session_running">Zatrzymaj sesję, zanim zresetujesz ustawienia.</string>
|
||||
<string name="setup_reset_settings_partial">Ustawienia zostały zresetowane, ale nie wszystkie. Szczegóły są w logach.</string>
|
||||
<string name="setup_offline">Tryb offline</string>
|
||||
<string name="setup_offline_auto">Automatyczny tryb offline</string>
|
||||
<string name="setup_sign_in_first">Najpierw zaloguj się do Steam</string>
|
||||
<string name="setup_launcher">Aplikacja</string>
|
||||
<string name="setup_language">Język</string>
|
||||
@@ -4160,4 +4161,7 @@
|
||||
<string name="theme_custom_error">Błąd</string>
|
||||
<string name="hud_only_during_game">Pokazuj HUD tylko podczas gry</string>
|
||||
<string name="hud_only_during_game_hint">Ukryj HUD, gdy nie wykryto klatek gry.</string>
|
||||
<string name="steam_store_close_steam">Najpierw zamknij Steam</string>
|
||||
<string name="steam_store_session_wait">Najpierw wstrzymaj pobieranie ze Steam</string>
|
||||
<string name="steam_store_linux_build">Ta gra instaluje swoją wersję dla Linuksa. Zainstaluj ją ze Steama.</string>
|
||||
</resources>
|
||||
@@ -917,6 +917,7 @@
|
||||
<string name="setup_log_export_failed">Não foi possível guardar os registos de sessão.</string>
|
||||
<string name="setup_log_delete_failed">Não foi possível eliminar os registos de sessão.</string>
|
||||
<string name="setup_offline">Modo offline</string>
|
||||
<string name="setup_offline_auto">Modo offline automático</string>
|
||||
<string name="setup_sign_in_first">Inicie sessão no Steam primeiro</string>
|
||||
<string name="setup_launcher">Iniciador</string>
|
||||
<string name="setup_language">Idioma</string>
|
||||
@@ -4119,4 +4120,7 @@
|
||||
<string name="drawer_antialiasing">Suavização de serrilhado</string>
|
||||
<string name="hud_only_during_game">Mostrar o HUD apenas durante um jogo</string>
|
||||
<string name="hud_only_during_game_hint">Ocultar o HUD quando não forem detetados fotogramas do jogo.</string>
|
||||
<string name="steam_store_close_steam">Feche primeiro o Steam</string>
|
||||
<string name="steam_store_session_wait">Coloque primeiro em pausa a transferência do Steam</string>
|
||||
<string name="steam_store_linux_build">Este jogo instala a sua versão para Linux. Instale-o a partir do Steam.</string>
|
||||
</resources>
|
||||
@@ -924,6 +924,7 @@
|
||||
<string name="setup_log_export_failed">Não foi possível salvar os registros de sessão.</string>
|
||||
<string name="setup_log_delete_failed">Não foi possível excluir os registros de sessão.</string>
|
||||
<string name="setup_offline">Modo offline</string>
|
||||
<string name="setup_offline_auto">Modo offline automático</string>
|
||||
<string name="setup_sign_in_first">Inicie sessão na Steam primeiro</string>
|
||||
<string name="setup_launcher">Inicializador</string>
|
||||
<string name="setup_language">Idioma</string>
|
||||
@@ -4127,4 +4128,7 @@
|
||||
<string name="drawer_antialiasing">Suavização de serrilhado</string>
|
||||
<string name="hud_only_during_game">Mostrar o HUD somente durante o jogo</string>
|
||||
<string name="hud_only_during_game_hint">Ocultar o HUD quando nenhum quadro do jogo for detectado.</string>
|
||||
<string name="steam_store_close_steam">Feche o Steam primeiro</string>
|
||||
<string name="steam_store_session_wait">Pause o download do Steam primeiro</string>
|
||||
<string name="steam_store_linux_build">Este jogo instala sua versão para Linux. Instale-o pelo Steam.</string>
|
||||
</resources>
|
||||
@@ -925,6 +925,7 @@
|
||||
<string name="setup_reset_settings_session_running">Oprește sesiunea înainte de a reseta setările.</string>
|
||||
<string name="setup_reset_settings_partial">Setările au fost resetate, dar nu toate. Detaliile sunt în jurnale.</string>
|
||||
<string name="setup_offline">Mod offline</string>
|
||||
<string name="setup_offline_auto">Mod offline automat</string>
|
||||
<string name="setup_sign_in_first">Autentifică-te mai întâi în Steam</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
<string name="setup_language">Limbă</string>
|
||||
@@ -4120,4 +4121,7 @@
|
||||
<string name="theme_custom_error">Eroare</string>
|
||||
<string name="hud_only_during_game">Afișează HUD-ul doar în timpul jocului</string>
|
||||
<string name="hud_only_during_game_hint">Ascunde HUD-ul când nu sunt detectate cadre ale jocului.</string>
|
||||
<string name="steam_store_close_steam">Închide mai întâi Steam</string>
|
||||
<string name="steam_store_session_wait">Pune mai întâi pe pauză descărcarea Steam</string>
|
||||
<string name="steam_store_linux_build">Acest joc își instalează versiunea pentru Linux. Instalează-l din Steam.</string>
|
||||
</resources>
|
||||
@@ -928,6 +928,7 @@
|
||||
<string name="setup_reset_settings_session_running">Остановите сессию перед сбросом настроек.</string>
|
||||
<string name="setup_reset_settings_partial">Настройки сброшены, но некоторые части сбросить не удалось. Подробности в журналах.</string>
|
||||
<string name="setup_offline">Автономный режим</string>
|
||||
<string name="setup_offline_auto">Автоматический автономный режим</string>
|
||||
<string name="setup_sign_in_first">Сначала войдите в Steam</string>
|
||||
<string name="setup_launcher">Лаунчер</string>
|
||||
<string name="setup_language">Язык</string>
|
||||
@@ -4161,4 +4162,7 @@
|
||||
<string name="theme_custom_error">Ошибка</string>
|
||||
<string name="hud_only_during_game">Показывать HUD только во время игры</string>
|
||||
<string name="hud_only_during_game_hint">Скрывать HUD, когда кадры игры не обнаруживаются.</string>
|
||||
<string name="steam_store_close_steam">Сначала закройте Steam</string>
|
||||
<string name="steam_store_session_wait">Сначала приостановите загрузку Steam</string>
|
||||
<string name="steam_store_linux_build">Эта игра устанавливает свою версию для Linux. Установите её из Steam.</string>
|
||||
</resources>
|
||||
@@ -922,6 +922,7 @@
|
||||
<string name="setup_reset_settings_session_running">Stoppa sessionen innan du återställer inställningar.</string>
|
||||
<string name="setup_reset_settings_partial">Inställningarna återställdes, men inte alla. Detaljerna finns i loggen.</string>
|
||||
<string name="setup_offline">Offlineläge</string>
|
||||
<string name="setup_offline_auto">Automatiskt offlineläge</string>
|
||||
<string name="setup_sign_in_first">Logga in på Steam först</string>
|
||||
<string name="setup_launcher">Startprogram</string>
|
||||
<string name="setup_language">Språk</string>
|
||||
@@ -4080,4 +4081,7 @@
|
||||
<string name="theme_custom_error">Fel</string>
|
||||
<string name="hud_only_during_game">Visa HUD endast under spel</string>
|
||||
<string name="hud_only_during_game_hint">Dölj HUD när inga spelbildrutor upptäcks.</string>
|
||||
<string name="steam_store_close_steam">Stäng Steam först</string>
|
||||
<string name="steam_store_session_wait">Pausa Steam-nedladdningen först</string>
|
||||
<string name="steam_store_linux_build">Det här spelet installerar sin Linux-version. Installera det från Steam.</string>
|
||||
</resources>
|
||||
@@ -919,6 +919,7 @@
|
||||
<string name="setup_reset_settings_session_running">หยุดเซสชันก่อนรีเซ็ตการตั้งค่า</string>
|
||||
<string name="setup_reset_settings_partial">รีเซ็ตการตั้งค่าแล้ว แต่ไม่ทั้งหมด รายละเอียดอยู่ในล็อก</string>
|
||||
<string name="setup_offline">โหมดออฟไลน์</string>
|
||||
<string name="setup_offline_auto">โหมดออฟไลน์อัตโนมัติ</string>
|
||||
<string name="setup_sign_in_first">ลงชื่อเข้าใช้ Steam ก่อน</string>
|
||||
<string name="setup_launcher">ตัวเปิดแอป</string>
|
||||
<string name="setup_language">ภาษา</string>
|
||||
@@ -4050,4 +4051,7 @@
|
||||
<string name="theme_custom_error">ข้อผิดพลาด</string>
|
||||
<string name="hud_only_during_game">แสดง HUD เฉพาะขณะเล่นเกม</string>
|
||||
<string name="hud_only_during_game_hint">ซ่อน HUD เมื่อไม่พบเฟรมของเกม</string>
|
||||
<string name="steam_store_close_steam">ปิด Steam ก่อน</string>
|
||||
<string name="steam_store_session_wait">หยุดการดาวน์โหลด Steam ชั่วคราวก่อน</string>
|
||||
<string name="steam_store_linux_build">เกมนี้ติดตั้งเวอร์ชัน Linux ของตัวเอง ให้ติดตั้งจาก Steam</string>
|
||||
</resources>
|
||||
@@ -914,6 +914,7 @@
|
||||
<string name="setup_log_export_failed">Oturum günlükleri kaydedilemedi.</string>
|
||||
<string name="setup_log_delete_failed">Oturum günlükleri silinemedi.</string>
|
||||
<string name="setup_offline">Çevrimdışı mod</string>
|
||||
<string name="setup_offline_auto">Otomatik çevrimdışı mod</string>
|
||||
<string name="setup_sign_in_first">Önce Steam\'de oturum açın</string>
|
||||
<string name="setup_launcher">Başlatıcı</string>
|
||||
<string name="setup_language">Dil</string>
|
||||
@@ -4080,4 +4081,7 @@
|
||||
<string name="theme_custom_error">Hata</string>
|
||||
<string name="hud_only_during_game">HUD\'yi yalnızca oyun sırasında göster</string>
|
||||
<string name="hud_only_during_game_hint">Oyun kareleri algılanmadığında HUD\'yi gizle.</string>
|
||||
<string name="steam_store_close_steam">Önce Steam\'i kapatın</string>
|
||||
<string name="steam_store_session_wait">Önce Steam indirmesini duraklatın</string>
|
||||
<string name="steam_store_linux_build">Bu oyun Linux sürümünü yükler. Steam\'den yükleyin.</string>
|
||||
</resources>
|
||||
@@ -928,6 +928,7 @@
|
||||
<string name="setup_reset_settings_session_running">Зупиніть сеанс перед скиданням налаштувань.</string>
|
||||
<string name="setup_reset_settings_partial">Налаштування скинуто, але не всі. Подробиці в журналах.</string>
|
||||
<string name="setup_offline">Офлайн-режим</string>
|
||||
<string name="setup_offline_auto">Автоматичний офлайн-режим</string>
|
||||
<string name="setup_sign_in_first">Спершу увійдіть у Steam</string>
|
||||
<string name="setup_launcher">Лаунчер</string>
|
||||
<string name="setup_language">Мова</string>
|
||||
@@ -4160,4 +4161,7 @@
|
||||
<string name="theme_custom_error">Помилка</string>
|
||||
<string name="hud_only_during_game">Показувати HUD лише під час гри</string>
|
||||
<string name="hud_only_during_game_hint">Приховувати HUD, коли кадри гри не виявляються.</string>
|
||||
<string name="steam_store_close_steam">Спочатку закрийте Steam</string>
|
||||
<string name="steam_store_session_wait">Спочатку призупиніть завантаження Steam</string>
|
||||
<string name="steam_store_linux_build">Ця гра встановлює свою версію для Linux. Установіть її зі Steam.</string>
|
||||
</resources>
|
||||
@@ -919,6 +919,7 @@
|
||||
<string name="setup_reset_settings_session_running">Dừng phiên trước khi đặt lại thiết lập.</string>
|
||||
<string name="setup_reset_settings_partial">Đã đặt lại thiết lập, nhưng chưa phải tất cả. Chi tiết có trong log.</string>
|
||||
<string name="setup_offline">Chế độ ngoại tuyến</string>
|
||||
<string name="setup_offline_auto">Chế độ ngoại tuyến tự động</string>
|
||||
<string name="setup_sign_in_first">Đăng nhập Steam trước</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
<string name="setup_language">Ngôn ngữ</string>
|
||||
@@ -4050,4 +4051,7 @@
|
||||
<string name="theme_custom_error">Lỗi</string>
|
||||
<string name="hud_only_during_game">Chỉ hiển thị HUD khi đang chơi</string>
|
||||
<string name="hud_only_during_game_hint">Ẩn HUD khi không phát hiện khung hình trò chơi.</string>
|
||||
<string name="steam_store_close_steam">Hãy đóng Steam trước</string>
|
||||
<string name="steam_store_session_wait">Hãy tạm dừng tải xuống Steam trước</string>
|
||||
<string name="steam_store_linux_build">Trò chơi này cài bản dành cho Linux. Hãy cài từ Steam.</string>
|
||||
</resources>
|
||||
@@ -919,6 +919,7 @@
|
||||
<string name="setup_reset_settings_session_running">请先停止会话再重置设置。</string>
|
||||
<string name="setup_reset_settings_partial">设置已重置,但部分内容未能重置。详情请查看日志。</string>
|
||||
<string name="setup_offline">离线模式</string>
|
||||
<string name="setup_offline_auto">自动离线模式</string>
|
||||
<string name="setup_sign_in_first">请先登录 Steam</string>
|
||||
<string name="setup_launcher">启动器</string>
|
||||
<string name="setup_language">语言</string>
|
||||
@@ -4050,4 +4051,7 @@
|
||||
<string name="theme_custom_error">错误</string>
|
||||
<string name="hud_only_during_game">仅在游戏期间显示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未检测到游戏帧时隐藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">请先关闭 Steam</string>
|
||||
<string name="steam_store_session_wait">请先暂停 Steam 下载</string>
|
||||
<string name="steam_store_linux_build">此游戏会安装其 Linux 版本。请通过 Steam 安装。</string>
|
||||
</resources>
|
||||
@@ -918,6 +918,7 @@
|
||||
<string name="setup_reset_settings_session_running">請先停止會話再重設設定。</string>
|
||||
<string name="setup_reset_settings_partial">設定已重設,但部分項目未能重設。詳情請查看記錄。</string>
|
||||
<string name="setup_offline">離線模式</string>
|
||||
<string name="setup_offline_auto">自動離線模式</string>
|
||||
<string name="setup_sign_in_first">請先登入 Steam</string>
|
||||
<string name="setup_launcher">啟動器</string>
|
||||
<string name="setup_language">語言</string>
|
||||
@@ -4050,4 +4051,7 @@
|
||||
<string name="theme_custom_error">錯誤</string>
|
||||
<string name="hud_only_during_game">只在遊戲期間顯示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">請先關閉 Steam</string>
|
||||
<string name="steam_store_session_wait">請先暫停 Steam 下載</string>
|
||||
<string name="steam_store_linux_build">此遊戲會安裝其 Linux 版本。請透過 Steam 安裝。</string>
|
||||
</resources>
|
||||
@@ -918,6 +918,7 @@
|
||||
<string name="setup_reset_settings_session_running">請先停止工作階段再重設設定。</string>
|
||||
<string name="setup_reset_settings_partial">設定已重設,但部分項目無法重設。詳細資訊請查看日誌。</string>
|
||||
<string name="setup_offline">離線模式</string>
|
||||
<string name="setup_offline_auto">自動離線模式</string>
|
||||
<string name="setup_sign_in_first">請先登入 Steam</string>
|
||||
<string name="setup_launcher">啟動器</string>
|
||||
<string name="setup_language">語言</string>
|
||||
@@ -4050,4 +4051,7 @@
|
||||
<string name="theme_custom_error">錯誤</string>
|
||||
<string name="hud_only_during_game">僅在遊戲期間顯示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">請先關閉 Steam</string>
|
||||
<string name="steam_store_session_wait">請先暫停 Steam 下載</string>
|
||||
<string name="steam_store_linux_build">此遊戲會安裝其 Linux 版本。請透過 Steam 安裝。</string>
|
||||
</resources>
|
||||
@@ -383,6 +383,7 @@
|
||||
<string name="mode_return_after_game">Return to DroidDeck after a game</string>
|
||||
<string name="mode_return_after_game_hint">When a game you started from DroidDeck or another launcher closes, Steam exits cleanly (cloud saves finish first) and you go back there. Off: stay in Steam.</string>
|
||||
<string name="mode_shader_precache">Shader pre-caching</string>
|
||||
<string name="mode_valve_proton_on_demand">Valve Proton only when needed</string>
|
||||
<string name="mode_shader_precache_hint">Steam downloads shaders prebuilt for your games and processes them in the background, so games stutter less. Off saves data, storage and battery; games build shaders as they play instead. The same setting as Steam’s Downloads > Shader Pre-Caching. Applies next session.</string>
|
||||
<string name="mode_steam_repair">Repair Steam client</string>
|
||||
<string name="mode_steam_repair_hint">Downloads the Steam client again the next time Steam starts. Use it if Steam stays on its loading screen. Games, sign-in and settings are kept.</string>
|
||||
@@ -1003,6 +1004,7 @@
|
||||
<string name="setup_reset_settings_session_running">Stop the session before resetting settings.</string>
|
||||
<string name="setup_reset_settings_partial">Settings were reset, but some parts could not be. The logs have the details.</string>
|
||||
<string name="setup_offline">Offline mode</string>
|
||||
<string name="setup_offline_auto">Auto offline mode</string>
|
||||
<string name="setup_sign_in_first">Sign in to Steam first</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
<string name="setup_language">Language</string>
|
||||
@@ -4388,4 +4390,7 @@
|
||||
<string name="hud_only_during_game_hint">Hide the HUD when no game frames are detected.</string>
|
||||
<string name="onboarding_button_getting_ready">Getting ready · %1$d%%</string>
|
||||
<string name="onboarding_button_finish">Finish setup · %1$d%%</string>
|
||||
<string name="steam_store_close_steam">Close Steam first</string>
|
||||
<string name="steam_store_session_wait">Pause the Steam download first</string>
|
||||
<string name="steam_store_linux_build">This game installs its Linux build. Install it from Steam.</string>
|
||||
</resources>
|
||||
Generated
+311
-7
@@ -8,6 +8,17 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-compression"
|
||||
version = "0.4.42"
|
||||
@@ -26,12 +37,24 @@ version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.11.1"
|
||||
@@ -47,6 +70,15 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-padding"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
@@ -65,6 +97,15 @@ version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
|
||||
|
||||
[[package]]
|
||||
name = "cbc"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
|
||||
dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.62"
|
||||
@@ -93,6 +134,16 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "combine"
|
||||
version = "4.6.7"
|
||||
@@ -120,6 +171,12 @@ version = "0.4.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
@@ -163,6 +220,23 @@ dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "data-encoding"
|
||||
version = "2.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"pem-rfc7468",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
@@ -170,7 +244,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"const-oid",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -188,20 +264,28 @@ dependencies = [
|
||||
name = "droiddeckstores"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"cbc",
|
||||
"cc",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"futures-util",
|
||||
"hmac",
|
||||
"jni",
|
||||
"libc",
|
||||
"lzma-rs",
|
||||
"rand 0.8.8",
|
||||
"reqwest",
|
||||
"rsa",
|
||||
"ruzstd",
|
||||
"serde_json",
|
||||
"sha1",
|
||||
"sha2",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"webpki-roots",
|
||||
"tungstenite",
|
||||
"webpki-roots 1.0.7",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -317,6 +401,15 @@ version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.4.1"
|
||||
@@ -389,7 +482,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower-service",
|
||||
"webpki-roots",
|
||||
"webpki-roots 1.0.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -528,6 +621,16 @@ dependencies = [
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||
dependencies = [
|
||||
"block-padding",
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.12.0"
|
||||
@@ -596,12 +699,27 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||
dependencies = [
|
||||
"spin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.186"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "litemap"
|
||||
version = "0.8.2"
|
||||
@@ -657,12 +775,66 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint-dig"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
"libm",
|
||||
"num-integer",
|
||||
"num-iter",
|
||||
"num-traits",
|
||||
"rand 0.8.8",
|
||||
"smallvec",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-iter"
|
||||
version = "0.1.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "pem-rfc7468"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
@@ -675,6 +847,27 @@ version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs1"
|
||||
version = "0.7.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
|
||||
dependencies = [
|
||||
"der",
|
||||
"pkcs8",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.5"
|
||||
@@ -731,7 +924,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.3.4",
|
||||
"lru-slab",
|
||||
"rand",
|
||||
"rand 0.9.4",
|
||||
"ring",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
@@ -772,14 +965,35 @@ version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.8.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha 0.3.1",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
"rand_chacha 0.9.0",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -789,7 +1003,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -836,7 +1059,7 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"webpki-roots",
|
||||
"webpki-roots 1.0.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -853,6 +1076,26 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rsa"
|
||||
version = "0.9.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"digest",
|
||||
"num-bigint-dig",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
"pkcs1",
|
||||
"pkcs8",
|
||||
"rand_core 0.6.4",
|
||||
"signature",
|
||||
"spki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.2"
|
||||
@@ -1007,6 +1250,16 @@ version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.9"
|
||||
@@ -1035,6 +1288,22 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
@@ -1255,6 +1524,26 @@ version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.26.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"data-encoding",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
"rand 0.9.4",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"sha1",
|
||||
"thiserror 2.0.18",
|
||||
"utf-8",
|
||||
"webpki-roots 0.26.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "twox-hash"
|
||||
version = "2.1.5"
|
||||
@@ -1291,6 +1580,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf-8"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.0.4"
|
||||
@@ -1412,6 +1707,15 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "0.26.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
|
||||
dependencies = [
|
||||
"webpki-roots 1.0.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.7"
|
||||
|
||||
@@ -10,11 +10,17 @@ name = "droiddeckstores"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
aes = "0.8"
|
||||
cbc = { version = "0.1", features = ["alloc", "block-padding"] }
|
||||
crc32fast = "1"
|
||||
hmac = "0.12"
|
||||
jni = "0.21"
|
||||
libc = "0.2"
|
||||
lzma-rs = { version = "0.3", default-features = false }
|
||||
lzma-rs = { version = "0.3", default-features = false, features = ["raw_decoder"] }
|
||||
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
|
||||
rand = "0.8"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "gzip"] }
|
||||
rsa = "0.9"
|
||||
tokio = { version = "1", default-features = false, features = ["rt", "net", "time", "sync", "io-util"] }
|
||||
futures-util = { version = "0.3", default-features = false, features = ["std"] }
|
||||
serde_json = { version = "1", features = ["preserve_order"] }
|
||||
@@ -23,6 +29,8 @@ sha2 = "0.10"
|
||||
tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }
|
||||
webpki-roots = "1"
|
||||
ruzstd = "0.8"
|
||||
tungstenite = { version = "0.26", default-features = false, features = ["handshake", "rustls-tls-webpki-roots"] }
|
||||
zeroize = "1"
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1"
|
||||
|
||||
@@ -2,19 +2,19 @@
|
||||
|
||||
The Kotlin side of the store download engines mirrors this file exactly. Every symbol the library
|
||||
exports is listed here with the class it binds to, the JNI signature, when it is called and on
|
||||
which thread. The GOG engine and the shared fetch core came from Bannerlator's
|
||||
`bl-steam-client` crate (method names and signatures match Bannerlator's `BlGogDownload`, only the
|
||||
package and class names changed). The Epic module (`src/epic/`) and the Amazon module
|
||||
which thread. The GOG engine, the shared fetch core and the Steam module (`src/steam/`, see its
|
||||
`NOTICE.md`) are derived from WinNative's `wn-steam-client` crate (GPL-3.0-or-later,
|
||||
https://github.com/WinNative-Emu/WinNative). The Epic module (`src/epic/`) and the Amazon module
|
||||
(`src/amazon/`) are DroidDeck's own, each written from a functional spec (see
|
||||
`docs/development/epic-cleanroom.md` and `docs/development/amazon-cleanroom.md`); their JNI
|
||||
surfaces below are new.
|
||||
surfaces below are new, as is the Steam one.
|
||||
|
||||
Load it once with `System.loadLibrary("droiddeckstores")`. The library is built by Gradle
|
||||
(`buildRustStores`, see `app/build.gradle`) and is absent from a `-PskipRust=true` build, so every
|
||||
call site must be ready for `UnsatisfiedLinkError` on `loadLibrary` or on the first `external`
|
||||
call and degrade to "store unavailable".
|
||||
|
||||
## Conventions that hold for all three engines
|
||||
## Conventions that hold for all engines
|
||||
|
||||
- The `external` functions are declared `@JvmStatic` in a Kotlin `object` (a `JClass` arrives as
|
||||
the second JNI argument). Declaring them in a plain `object` without `@JvmStatic` also binds —
|
||||
@@ -290,9 +290,207 @@ absent or that of empty input are created without a request. `.amazon_download_i
|
||||
created when a run starts and removed when it succeeds, which also creates
|
||||
`.amazon_download_complete`; nothing reads either marker.
|
||||
|
||||
## `com.droiddeck.launcher.stores.steam.SteamNative`
|
||||
|
||||
Steam store engine (`src/steam/`): signs in with the Linux Steam client's saved login, lists the
|
||||
account's games, plans and downloads a game straight into the Steam library folder the client
|
||||
uses, then writes what the client writes on completion, so the client sees the game as installed
|
||||
and does not update or verify it. Kotlin runs downloads and uninstalls only while the Steam client
|
||||
is closed.
|
||||
|
||||
```kotlin
|
||||
package com.droiddeck.launcher.stores.steam
|
||||
|
||||
object SteamNative {
|
||||
@JvmStatic external fun nativeSignIn(steamRootsJson: String, registryVdfPath: String, caBundlePath: String): String
|
||||
@JvmStatic external fun nativeSignOut()
|
||||
@JvmStatic external fun nativeLibrary(): String
|
||||
@JvmStatic external fun nativePlan(appId: Int, language: String): String
|
||||
@JvmStatic external fun nativeStart(appId: Int, language: String, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String, journalDir: String, caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: Any): Long
|
||||
@JvmStatic external fun nativeCancel(handle: Long)
|
||||
@JvmStatic external fun nativeRelease(handle: Long)
|
||||
@JvmStatic external fun nativeUninstall(appId: Int, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String): String
|
||||
}
|
||||
```
|
||||
|
||||
| Method | JNI signature | Symbol suffix |
|
||||
|---|---|---|
|
||||
| `nativeSignIn(steamRootsJson, registryVdfPath, caBundlePath): String` | `(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;` | `nativeSignIn` |
|
||||
| `nativeSignOut()` | `()V` | `nativeSignOut` |
|
||||
| `nativeLibrary(): String` | `()Ljava/lang/String;` | `nativeLibrary` |
|
||||
| `nativePlan(appId, language): String` | `(ILjava/lang/String;)Ljava/lang/String;` | `nativePlan` |
|
||||
| `nativeStart(...)`: Long | `(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IILjava/lang/Object;)J` | `nativeStart` |
|
||||
| `nativeCancel(handle: Long)` | `(J)V` | `nativeCancel` |
|
||||
| `nativeRelease(handle: Long)` | `(J)V` | `nativeRelease` |
|
||||
| `nativeUninstall(appId, steamRoot, gameLibraryHost, gameLibraryGuest, libraryRootsJson): String` | `(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;` | `nativeUninstall` |
|
||||
|
||||
Full symbols are `Java_com_droiddeck_launcher_stores_steam_SteamNative_<suffix>`. Every `String`
|
||||
answer is a UTF-8 JSON object with `"ok": true|false`; a failure carries `"error": "<short
|
||||
reason>"`. `nativeSignIn`, `nativeLibrary`, `nativePlan` and `nativeUninstall` block on the
|
||||
network or the disk: call them off the main thread. A Rust panic is caught at the boundary and
|
||||
answers `{"ok":false,"error":"internal_error"}`.
|
||||
|
||||
Paths: "host" paths are Android paths the app can open; "guest" paths are what the Steam client
|
||||
sees inside proot (what `libraryfolders.vdf` holds). `libraryRootsJson` is a JSON array of
|
||||
`{"host": "...", "guest": "..."}`, one per library of the active client; it is used to find shared
|
||||
app folders and `libraryfolders.vdf` entries, and the game library is added to it when missing.
|
||||
|
||||
### `nativeSignIn`
|
||||
|
||||
`steamRootsJson`: JSON array of host paths of Steam roots (arm64 and x86-64 clients), searched in
|
||||
order. `registryVdfPath`: host path of `~/.steam/registry.vdf` (`""` = none). `caBundlePath`: see
|
||||
conventions (used for the CM directory request).
|
||||
|
||||
Reads, never writes: `<root>/config/loginusers.vdf` (accounts), `<root>/local.vdf`
|
||||
(`MachineUserConfigStore/Software/Valve/Steam/ConnectCache`, keys matched case-insensitively; the
|
||||
entry whose key starts with the 8-hex-digit CRC32 of the lowercased account name), and
|
||||
`registry.vdf` (`Registry/HKCU/Software/Valve/Steam/AutoLoginUser`). The account is
|
||||
`AutoLoginUser` when it names a known account, else the one with `MostRecent` `"1"`, else the
|
||||
newest `Timestamp`. The token is decrypted in memory (key = SHA-256 of the lowercased account
|
||||
name; AES-256-ECB-wrapped IV, AES-256-CBC + PKCS#7), checked to be a Steam JWT for that
|
||||
SteamID64, sent once in the CM logon and zeroized. It is never logged, written, renewed or
|
||||
replaced.
|
||||
|
||||
Answers `{"ok":true,"account":"<AccountName>","steamId":"<SteamID64>"}` or
|
||||
`{"ok":false,"error":…}` with `no_saved_login` (no account in any `loginusers.vdf`),
|
||||
`remember_me_off` (`RememberPassword` `"0"`, or no ConnectCache entry: signed out),
|
||||
`decrypt_failed` (the entry does not decrypt to this account's token), or `logon_failed: …`
|
||||
(`logon_failed: eresult=<n> <name>` when Steam refused the logon, e.g. `eresult=5
|
||||
InvalidPassword` for an expired token; otherwise a connection reason). One process-wide session:
|
||||
a second call while it is logged on answers at once with the same account. After logon the
|
||||
session sends no persona, friends or presence messages.
|
||||
|
||||
`nativeSignOut()` logs off and drops the session; it never touches the client's files.
|
||||
|
||||
### `nativeLibrary`
|
||||
|
||||
`{"ok":true,"games":[{"appId":291550,"name":"Brawlhalla","installDir":"Brawlhalla","type":"game","free":true}…]}`:
|
||||
every app the account's licenses grant (package 0, the basic Steam license, is skipped) whose
|
||||
PICS `common.type` is `game`, sorted by name. `free` = appinfo marks it free to play
|
||||
(`common.freetogame` or `extended.isfreeapp` `"1"`). Loaded once per session (the first call
|
||||
fetches PICS for every owned app and can take a while). `not_signed_in` without a session.
|
||||
|
||||
### `nativePlan`
|
||||
|
||||
What `nativeStart` would install for `appId` with `language` (Steam's language names, e.g.
|
||||
`english`):
|
||||
|
||||
```json
|
||||
{"ok":true,"appId":291550,"name":"Brawlhalla","installDir":"Brawlhalla","buildId":26465982,
|
||||
"language":"english","linuxBuild":false,"downloadBytes":…,"installBytes":1594368732,
|
||||
"depots":[{"depotId":291551,"manifestId":"4224536525702420323","size":1565156559,"dlcAppId":0}],
|
||||
"shared":[{"depotId":228988,"fromAppId":228980,"manifestId":"6645201662696499616","size":29212173}]}
|
||||
```
|
||||
|
||||
Selection (what the client picks for a Windows game run through Proton): `config.oslist` empty or
|
||||
containing `windows`; `config.osarch` empty or `64` (`32` only when no `64` depot exists);
|
||||
`config.language` empty or the language (english when the game has no depot for the requested
|
||||
language but has english ones; the answer's `language` is the one used); no `lowviolence`
|
||||
depots; for an owned app, only depots one of the account's packages grants (`depotids`), as
|
||||
the client installs no other; DLC depots (`dlcappid`) only when the DLC is owned; `depotfromapp`/`sharedinstall`
|
||||
depots are listed under `shared` with the owning app (e.g. 228980 Steamworks Common
|
||||
Redistributables), whose public manifest they use. Manifest gids are the public branch's, sizes
|
||||
come from PICS, `buildId` is the public branch's. `installBytes`/`downloadBytes` include the
|
||||
shared depots (they are not checked against what is already installed here). Errors:
|
||||
`not_signed_in`, `not_owned`, `appinfo unavailable`, `appinfo unavailable for shared app <id>`,
|
||||
`no installable Windows depot`, `linux_build` (no Windows depot, and the game has a Linux build). A free app
|
||||
the account does not own yet is planned without asking for its license. `linuxBuild` is true
|
||||
when `common.oslist` lists `linux`: the client then installs the Linux build unless the game is
|
||||
mapped to a Proton, so the caller checks that mapping before installing.
|
||||
|
||||
### `nativeStart`
|
||||
|
||||
Parameters: `appId`, `language`, `steamRoot` (host path of the active client's Steam root; its
|
||||
`steamapps/` and `config/` hold the two `libraryfolders.vdf` copies, `depotcache/` its cached
|
||||
manifests), `gameLibraryHost`/`gameLibraryGuest` (the library to install into), `libraryRootsJson`,
|
||||
`journalDir` (app-private directory for resume journals), `caBundlePath`, `maxWorkers` (request
|
||||
window ceiling; `0` = 16), `processWorkers` (decrypt/decompress/write threads; `0` = half the
|
||||
cores, 2 to 6; on SD cards the card writes, not the network, tend to be the limit), `listener`.
|
||||
|
||||
Returns `0` without any callback when the listener is null, `appId <= 0`, the JavaVM or a global
|
||||
ref cannot be obtained, `steamRoot`/`gameLibraryHost`/`gameLibraryGuest`/`journalDir` is empty,
|
||||
or the worker thread cannot be spawned. Otherwise the run is on a thread named `steam-dl`
|
||||
(background priority) and `onComplete` fires exactly once, last. `nativeCancel` is idempotent and
|
||||
safe until `nativeRelease`; call `nativeRelease` exactly once per non-zero handle, after
|
||||
`onComplete`.
|
||||
|
||||
| Listener method | JNI signature | When |
|
||||
|---|---|---|
|
||||
| `onProgress(doneBytes: Long, totalBytes: Long, phase: String)` | `(JJLjava/lang/String;)V` | `phase` is `preparing` (sign-in check, plan, takeover, keys, manifests; `0`/`0`), `downloading` (the game's depots), `shared` (shared depots) or `registering`. `doneBytes`/`totalBytes` count the depot files (decompressed) of everything this run installs, shared depots included; chunks already correct on disk count as done. At most every 250 ms, plus at every phase change and depot end. |
|
||||
| `onComplete(ok: Boolean, result: String)` | `(ZLjava/lang/String;)V` | `{"ok":true,"alreadyInstalled":false}` after a download, `{"ok":true,"alreadyInstalled":true}` when the game was already fully installed at the current build (nothing downloaded or written), or `{"ok":false,"error":"…"}`: `cancelled`, `not_signed_in`, `already_running` (a run for the same app is active), `not_owned`, `free_license_refused`, `library_not_in_libraryfolders` (no `libraryfolders.vdf` entry has the guest path), `not_enough_space: need … MiB, have … MiB`, `access_denied: depot <id>`, or a short message for network and disk failures. |
|
||||
|
||||
What a run does, in order:
|
||||
|
||||
1. Plans as `nativePlan`; a free app the account does not own is first added to the account with
|
||||
`CMsgClientRequestFreeLicense`.
|
||||
2. Takeover check on `<gameLibraryHost>/steamapps/appmanifest_<appId>.acf`: absent → fresh
|
||||
install; `StateFlags` has 4 and none of the update/download/validate bits and `buildid` is the
|
||||
current build → `alreadyInstalled`; a build on disk at another build (the fully-installed bit
|
||||
set, even with an update pending) → `update_in_steam`, left to the Steam client; otherwise (a
|
||||
half-finished client download) `steamapps/downloading/<appId>` and `steamapps/temp/<appId>`
|
||||
are deleted and the journal is discarded, while the manifest is kept so registration merges
|
||||
its settings.
|
||||
3. Downloads the game's depots in place into `<gameLibraryHost>/steamapps/common/<installdir>`:
|
||||
no temp files, no space reservation, each file trimmed to its exact size when its last chunk
|
||||
lands. A chunk used several times is fetched once. Files already on disk are read back chunk by
|
||||
chunk and only wrong or missing chunks are fetched (resume, update, taking over a client's
|
||||
partial files).
|
||||
4. Shared depots go into the library that holds `appmanifest_<fromAppId>.acf` (else the Steam
|
||||
root's own library), folder `steamapps/common/<that app's installdir>`; a shared depot already
|
||||
installed at the planned manifest is skipped.
|
||||
5. Registers: writes `appmanifest_<appId>.acf` (keys in the client's order: `appid`, `Universe`,
|
||||
`name`, `StateFlags` 4, `installdir`, `LastUpdated`, `LastPlayed`, `SizeOnDisk` (the game's
|
||||
depots), `StagingSize`, `buildid`, `LastOwner` (SteamID64), `DownloadType` 1, `UpdateResult`,
|
||||
`BytesToDownload`/`BytesDownloaded` (compressed size of every installed depot, shared
|
||||
included), `BytesToStage`/`BytesStaged` (installed size of the game's depots plus the shared
|
||||
depots installed in this run), `TargetBuildID`, `AutoUpdateBehavior`,
|
||||
`AllowOtherDownloadsWhileRunning`, `ScheduledAutoUpdate`, `InstalledDepots`
|
||||
(`manifest`, `size`, plus `dlcappid` for DLC depots), `InstallScripts` when a game depot has
|
||||
one, `SharedDepots`, `UserConfig`/`MountedConfig` `language`), merging into an existing file
|
||||
(unknown keys, `LastPlayed` and the auto-update settings are kept). Updates the shared app's
|
||||
manifest (`SizeOnDisk`, `InstalledDepots`, `InstallScripts` entry such as
|
||||
`"228988" "_CommonRedist\\vcredist\\2019\\installscript.vdf"`; created when missing).
|
||||
Adds `"<appId>" "0"` under `apps` of the matching entry in both
|
||||
`<steamRoot>/steamapps/libraryfolders.vdf` and `<steamRoot>/config/libraryfolders.vdf` (the
|
||||
client fills in the size later); nothing else there changes. All files are written through a
|
||||
temp file + rename.
|
||||
|
||||
Never written: `config.vdf`, `localconfig.vdf`, `registry.vdf` (the client regenerates them) and
|
||||
`depotcache/` (the client keeps manifests there with decrypted file names, not in the CDN form
|
||||
this engine caches; it fetches them when it needs them).
|
||||
|
||||
On-disk protocol of the journal: `<journalDir>/<appId>/<libraryHash>/depot.config` (JSON:
|
||||
`buildId`, the finished manifest per depot or an in-progress sentinel) and
|
||||
`<depot>_<manifest>.manifest` (raw CDN manifests) beside it. `<libraryHash>` is the CRC32, as 8
|
||||
lowercase hex digits, of `gameLibraryGuest` with trailing `/` removed, so a resume in one library
|
||||
never trusts depots finished in another. A cancelled or failed run keeps it, and the next `nativeStart` for the same app
|
||||
resumes (finished depots are skipped, the rest is checked on disk); a journal written for another
|
||||
build is dropped. It is deleted after a successful registration. Nothing extra is ever left in
|
||||
the game folder.
|
||||
|
||||
### `nativeUninstall`
|
||||
|
||||
Matches the client's own uninstall: deletes `<gameLibraryHost>/steamapps/common/<installdir>` and
|
||||
the game's `appmanifest_<appId>.acf`, `<steamRoot>/depotcache/<depot>_<manifest>.manifest` for
|
||||
the game's `InstalledDepots` and `<steamRoot>/steamapps/shadercache/<appId>`; keeps
|
||||
`steamapps/compatdata/<appId>` (the Proton prefix, i.e. saves). For each of the game's
|
||||
`SharedDepots` that no other installed game in any library lists, deletes that depot's files from
|
||||
the shared app's folder (empty folders stay, as with the client) and removes its
|
||||
`InstalledDepots` and `InstallScripts` entries and its size from the shared app's manifest. The
|
||||
file list comes from the client's `depotcache` copy of that manifest, else from the CDN through
|
||||
the live session; without either the shared depot is left installed and listed in `keptShared`.
|
||||
Removes the app from `apps` in both `libraryfolders.vdf` copies.
|
||||
|
||||
Answers `{"ok":true,"removedShared":[228988],"keptShared":[]}`, or `{"ok":false,"error":…}`:
|
||||
`not_installed` (no app manifest), `bad installdir in app manifest`, `bad arguments`, or a disk
|
||||
error.
|
||||
|
||||
## Log tags
|
||||
|
||||
Lines go to logcat under `GogNative` and `EpicNative` (the Amazon module logs only through
|
||||
`onLog`). Bannerlator used `BL_GOG_DL` for the GOG engine; the fetch core's line grammar
|
||||
(`fetch-start`, `fetch-window`, `throughput`, `fetch-end`, `summary`) is unchanged, so its tuning
|
||||
notes still read against a DroidDeck log.
|
||||
|
||||
The Steam module logs under `DroidDeckSteam` and never logs a token; its chunk downloads go
|
||||
through the fetch core with the label `steam depot=<id>`.
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Ported from Bannerlator's bl-steam-client crate (GPL-3.0-or-later), itself derived from WinNative's wn-steam-client.
|
||||
//! DroidDeck's store download engines. The Steam client and the shared fetch core are derived from WinNative's wn-steam-client (GPL-3.0-or-later, https://github.com/WinNative-Emu/WinNative).
|
||||
|
||||
#![allow(clippy::missing_safety_doc, clippy::result_large_err)]
|
||||
|
||||
@@ -11,4 +11,5 @@ pub mod fetch_tuning;
|
||||
pub mod gog;
|
||||
pub mod md5_small;
|
||||
pub mod priority;
|
||||
pub mod steam;
|
||||
pub mod stores_jni;
|
||||
@@ -0,0 +1,50 @@
|
||||
# Steam store engine: provenance and license notice
|
||||
|
||||
The Steam module of `libdroiddeckstores.so` (`app/src/main/rust/stores/src/steam/`) is a
|
||||
**derivative work of the `wn-steam-client` crate from the WinNative project**,
|
||||
<https://github.com/WinNative-Emu/WinNative>, directory
|
||||
`app/src/main/cpp/wn-steam-client/rust`, taken at upstream commit `a2020b7` (2026-09-01).
|
||||
The upstream crate is published under **GPL-3.0-or-later**; this derivative is distributed under
|
||||
the same license as part of DroidDeck. Copyright in the original code remains with the WinNative
|
||||
authors and contributors, including maxjivi05.
|
||||
|
||||
The shared fetch core (`src/fetch_core.rs`, `src/fetch_tuning.rs`) and `src/md5_small.rs`, which
|
||||
this module uses, come from the same upstream crate.
|
||||
|
||||
## Modifications made in DroidDeck (GPL-3.0 §5(a) statement of changes)
|
||||
|
||||
Date of modification: 2026-11-07.
|
||||
|
||||
- Ported into the `droiddeckstores` crate as the module `steam`; identifiers, log tag
|
||||
(`DroidDeckSteam`) and thread name (`steam-dl`) follow DroidDeck naming.
|
||||
- Kept, with import paths adapted: WebSocket transport (`ws_connection`, `transport`), channel
|
||||
encryption and handshake (`encrypted_channel`, `handshake_messages`, `crypto`, `key_dictionary`),
|
||||
CM server discovery (`cm_server`, `cm_server_list`, `steam_directory`), wire formats
|
||||
(`emsg`, `cmsg_protobuf_header`, `proto_envelope`, `proto_wire`, `wire_format`, `base64`, `vdf`),
|
||||
`heartbeat`, `job_manager`, `content_manifest`, `depot_chunk`, and the protobuf messages for
|
||||
logon, licenses, PICS, depot keys, manifest request codes, CDN servers and free licenses.
|
||||
- `cm_client` reduced to logon with a refresh token, heartbeat, log-off and the download-store
|
||||
requests; the logon sends `machine_id` `DroidDeck-Steam`; logon and log-off EResults are kept
|
||||
for error reporting.
|
||||
- `cm_runtime`: no persona or friends traffic after logon, the C-ABI bridge (`cm_bridge`) is
|
||||
removed, and outbound messages are cleared from memory once sent.
|
||||
- Blocking HTTP replaced by a one-shot request helper (`http`); `cdn_client` reduced to `cdn`
|
||||
(URLs, manifest and HTTP-delivered appinfo fetches); CDN servers are de-duplicated by host,
|
||||
capped at 10 and filtered by `allowed_app_ids`.
|
||||
- `depot_writer` rewritten on DroidDeck's shared fetch core: files are written in place without
|
||||
`fallocate` or zero-fill and trimmed with `set_len`; the number of decode/write workers is a
|
||||
parameter; a chunk used in several places is fetched once; on resume, chunks on disk are read
|
||||
back and checked before anything is fetched.
|
||||
- `depot_config` / `depot_downloader`: the resume journal moved out of the game folder into a
|
||||
caller-given directory, keyed by app and build; the progress sidecar and clean-pause markers are
|
||||
dropped.
|
||||
- New: `signin` (reuse of the Linux Steam client's saved login), `session` (one process-wide CM
|
||||
session), `library`, `plan` (depot selection), `register` (app manifests, shared depots,
|
||||
`libraryfolders.vdf`, takeover of half-finished client downloads, uninstall), `kv` (Valve
|
||||
KeyValues writer), `install` (download orchestration) and a new JNI layer (`jni`).
|
||||
- `library` records the depots the account's packages grant, and `plan` installs only those
|
||||
(the client skips the rest, e.g. edition-only depots); `plan` flags apps with a Linux build.
|
||||
- Not ported: QR and password sign-in, auth sessions, friends, chat and chat images, persona,
|
||||
lobbies, cloud, user stats, achievements, inventory, published files and workshop, app and
|
||||
ownership tickets, playing-session control, the Wine bridge, the other stores' downloaders,
|
||||
the version module and the original JNI layer.
|
||||
@@ -0,0 +1,97 @@
|
||||
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
pub fn encode(bytes: &[u8]) -> String {
|
||||
if bytes.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
|
||||
let (chunks, remainder) = bytes.as_chunks::<3>();
|
||||
for chunk in chunks {
|
||||
let v = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | chunk[2] as u32;
|
||||
out.push(ALPHABET[((v >> 18) & 0x3f) as usize] as char);
|
||||
out.push(ALPHABET[((v >> 12) & 0x3f) as usize] as char);
|
||||
out.push(ALPHABET[((v >> 6) & 0x3f) as usize] as char);
|
||||
out.push(ALPHABET[(v & 0x3f) as usize] as char);
|
||||
}
|
||||
|
||||
match remainder {
|
||||
[a] => {
|
||||
let v = (*a as u32) << 16;
|
||||
out.push(ALPHABET[((v >> 18) & 0x3f) as usize] as char);
|
||||
out.push(ALPHABET[((v >> 12) & 0x3f) as usize] as char);
|
||||
out.push('=');
|
||||
out.push('=');
|
||||
}
|
||||
[a, b] => {
|
||||
let v = ((*a as u32) << 16) | ((*b as u32) << 8);
|
||||
out.push(ALPHABET[((v >> 18) & 0x3f) as usize] as char);
|
||||
out.push(ALPHABET[((v >> 12) & 0x3f) as usize] as char);
|
||||
out.push(ALPHABET[((v >> 6) & 0x3f) as usize] as char);
|
||||
out.push('=');
|
||||
}
|
||||
[] => {}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
pub fn decode(s: &str) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::with_capacity((s.len() / 4) * 3 + 3);
|
||||
let mut acc = 0u32;
|
||||
let mut bits = 0u32;
|
||||
|
||||
for b in s.bytes() {
|
||||
let v = value_of(b)?;
|
||||
let Some(v) = v else {
|
||||
continue;
|
||||
};
|
||||
acc = (acc << 6) | v as u32;
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push(((acc >> bits) & 0xff) as u8);
|
||||
}
|
||||
}
|
||||
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn value_of(b: u8) -> Option<Option<u8>> {
|
||||
match b {
|
||||
b'A'..=b'Z' => Some(Some(b - b'A')),
|
||||
b'a'..=b'z' => Some(Some(b - b'a' + 26)),
|
||||
b'0'..=b'9' => Some(Some(b - b'0' + 52)),
|
||||
b'+' | b'-' => Some(Some(62)),
|
||||
b'/' | b'_' => Some(Some(63)),
|
||||
b'=' | b' ' | b'\t' | b'\n' | b'\r' => Some(None),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn encodes_rfc4648_padding() {
|
||||
assert_eq!(encode(b""), "");
|
||||
assert_eq!(encode(b"f"), "Zg==");
|
||||
assert_eq!(encode(b"fo"), "Zm8=");
|
||||
assert_eq!(encode(b"foo"), "Zm9v");
|
||||
assert_eq!(encode(b"foobar"), "Zm9vYmFy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_standard_urlsafe_and_whitespace() {
|
||||
assert_eq!(decode("Zm9v YmFy"), Some(b"foobar".to_vec()));
|
||||
assert_eq!(decode("SGVsbG8td29ybGQ_"), Some(b"Hello-world?".to_vec()));
|
||||
assert_eq!(decode("Zg=="), Some(b"f".to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_character_fails() {
|
||||
assert_eq!(decode("Zm9v*"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
//! SteamPipe CDN: URL formation, manifest + HTTP-delivered appinfo fetches, and the zip/gzip
|
||||
//! helpers they need. Chunk bodies are fetched by the shared fetch core (`crate::fetch_core`).
|
||||
|
||||
use crate::steam::pb::ccontentserverdirectory::CContentServerDirectoryServerInfo;
|
||||
use flate2::read::{DeflateDecoder, GzDecoder};
|
||||
use std::io::Read;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Distinct CDN hosts a depot run spreads over. Each chunk carries one URL per host, so this also
|
||||
/// bounds the per-chunk URL memory.
|
||||
pub const MAX_CDN_HOSTS: usize = 10;
|
||||
|
||||
pub const MAX_MANIFEST_FETCH_ATTEMPTS: usize = 5;
|
||||
|
||||
/// Largest decompressed manifest accepted; real ones are at most tens of MiB.
|
||||
pub const MAX_MANIFEST_BYTES: usize = 512 * 1024 * 1024;
|
||||
/// Largest decompressed HTTP-delivered appinfo accepted.
|
||||
pub const MAX_APPINFO_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct CdnManifestResult {
|
||||
pub raw_manifest: Vec<u8>,
|
||||
pub error: String,
|
||||
pub http_status: i32,
|
||||
}
|
||||
|
||||
impl CdnManifestResult {
|
||||
pub fn ok(&self) -> bool {
|
||||
self.error.is_empty() && !self.raw_manifest.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_timeout() -> Duration {
|
||||
Duration::from_secs(30)
|
||||
}
|
||||
|
||||
pub fn build_manifest_url(
|
||||
server: &CContentServerDirectoryServerInfo,
|
||||
depot_id: u32,
|
||||
manifest_id: u64,
|
||||
request_code: u64,
|
||||
) -> Result<String, String> {
|
||||
let host = preferred_host(server).ok_or_else(|| "cdn server has no host".to_string())?;
|
||||
let mut url = format!(
|
||||
"{}://{}:{}/depot/{}/manifest/{}/5",
|
||||
if server.use_https() { "https" } else { "http" },
|
||||
host,
|
||||
server.port(),
|
||||
depot_id,
|
||||
manifest_id
|
||||
);
|
||||
if request_code != 0 {
|
||||
url.push('/');
|
||||
url.push_str(&request_code.to_string());
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
pub fn build_chunk_url(
|
||||
server: &CContentServerDirectoryServerInfo,
|
||||
depot_id: u32,
|
||||
chunk_sha: &[u8],
|
||||
) -> Result<String, String> {
|
||||
if chunk_sha.is_empty() {
|
||||
return Err("empty chunk sha".to_string());
|
||||
}
|
||||
let host = preferred_host(server).ok_or_else(|| "cdn server has no host".to_string())?;
|
||||
Ok(format!(
|
||||
"{}://{}:{}/depot/{}/chunk/{}",
|
||||
if server.use_https() { "https" } else { "http" },
|
||||
host,
|
||||
server.port(),
|
||||
depot_id,
|
||||
hex_encode(chunk_sha)
|
||||
))
|
||||
}
|
||||
|
||||
/// The per-host key the fetch core caps concurrency on (vhost when present, as the URL uses it).
|
||||
pub fn host_key(server: &CContentServerDirectoryServerInfo) -> String {
|
||||
preferred_host(server).unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// Usable servers (not China-only, with a host), de-duplicated by host key, in directory order,
|
||||
/// at most [`MAX_CDN_HOSTS`].
|
||||
pub fn usable_servers(
|
||||
servers: &[CContentServerDirectoryServerInfo],
|
||||
) -> Vec<CContentServerDirectoryServerInfo> {
|
||||
let mut out: Vec<CContentServerDirectoryServerInfo> = Vec::new();
|
||||
for server in servers {
|
||||
if server.steam_china_only || server.host.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let key = host_key(server);
|
||||
if out.iter().any(|s| host_key(s) == key) {
|
||||
continue;
|
||||
}
|
||||
out.push(server.clone());
|
||||
if out.len() >= MAX_CDN_HOSTS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn fetch_manifest(
|
||||
server: &CContentServerDirectoryServerInfo,
|
||||
depot_id: u32,
|
||||
manifest_id: u64,
|
||||
request_code: u64,
|
||||
ca_bundle_path: &str,
|
||||
timeout: Duration,
|
||||
) -> CdnManifestResult {
|
||||
let url = match build_manifest_url(server, depot_id, manifest_id, request_code) {
|
||||
Ok(url) => url,
|
||||
Err(error) => {
|
||||
return CdnManifestResult {
|
||||
error,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
};
|
||||
match crate::steam::http::get(&url, timeout, ca_bundle_path) {
|
||||
Ok(response) => validate_manifest_response(
|
||||
response.status as i32,
|
||||
response.body,
|
||||
response.content_length,
|
||||
),
|
||||
Err(error) => CdnManifestResult {
|
||||
error,
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries the servers in order (wrapping) with the shared back-off, up to
|
||||
/// [`MAX_MANIFEST_FETCH_ATTEMPTS`] attempts.
|
||||
pub fn fetch_manifest_with_retry(
|
||||
servers: &[CContentServerDirectoryServerInfo],
|
||||
depot_id: u32,
|
||||
manifest_id: u64,
|
||||
request_code: u64,
|
||||
ca_bundle_path: &str,
|
||||
cancel: &std::sync::atomic::AtomicBool,
|
||||
) -> CdnManifestResult {
|
||||
if servers.is_empty() {
|
||||
return CdnManifestResult {
|
||||
error: "no CDN servers available".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
let mut last = CdnManifestResult::default();
|
||||
for attempt in 0..MAX_MANIFEST_FETCH_ATTEMPTS {
|
||||
if attempt > 0 {
|
||||
std::thread::sleep(Duration::from_millis(
|
||||
crate::fetch_tuning::retry_backoff_millis(attempt as u32),
|
||||
));
|
||||
}
|
||||
if cancel.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
return CdnManifestResult {
|
||||
error: "cancelled".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
let server = &servers[attempt % servers.len()];
|
||||
last = fetch_manifest(
|
||||
server,
|
||||
depot_id,
|
||||
manifest_id,
|
||||
request_code,
|
||||
ca_bundle_path,
|
||||
default_timeout(),
|
||||
);
|
||||
if last.ok() {
|
||||
return last;
|
||||
}
|
||||
}
|
||||
last
|
||||
}
|
||||
|
||||
/// HTTP-delivered PICS appinfo URL (large appinfo the CM did not inline).
|
||||
pub fn build_appinfo_url(http_host: &str, app_id: u32, sha: &[u8]) -> String {
|
||||
format!(
|
||||
"http://{}/appinfo/{}/sha/{}.txt.gz",
|
||||
http_host,
|
||||
app_id,
|
||||
hex_encode(sha)
|
||||
)
|
||||
}
|
||||
|
||||
/// Fetch + gunzip an HTTP-delivered appinfo blob (same VDF as an inline `buffer`).
|
||||
pub fn fetch_appinfo(
|
||||
http_host: &str,
|
||||
app_id: u32,
|
||||
sha: &[u8],
|
||||
ca_bundle_path: &str,
|
||||
timeout: Duration,
|
||||
) -> Option<Vec<u8>> {
|
||||
if http_host.is_empty() || sha.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let url = build_appinfo_url(http_host, app_id, sha);
|
||||
let response = crate::steam::http::get(&url, timeout, ca_bundle_path).ok()?;
|
||||
if response.status != 200 || response.body.is_empty() {
|
||||
return None;
|
||||
}
|
||||
maybe_gunzip(response.body, MAX_APPINFO_BYTES)
|
||||
}
|
||||
|
||||
pub fn validate_manifest_response(
|
||||
http_status: i32,
|
||||
body: Vec<u8>,
|
||||
content_length: Option<u64>,
|
||||
) -> CdnManifestResult {
|
||||
if http_status != 200 {
|
||||
return CdnManifestResult {
|
||||
http_status,
|
||||
error: format!("HTTP status {http_status}"),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
if let Some(expected) = content_length {
|
||||
if body.len() as u64 != expected {
|
||||
return CdnManifestResult {
|
||||
http_status,
|
||||
error: "manifest body truncated (length mismatch)".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
}
|
||||
let Some(raw_manifest) = unzip_first_entry(&body, MAX_MANIFEST_BYTES) else {
|
||||
return CdnManifestResult {
|
||||
http_status,
|
||||
error: "manifest unzip failed".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
};
|
||||
CdnManifestResult {
|
||||
raw_manifest,
|
||||
error: String::new(),
|
||||
http_status,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first entry of a zip, refused when it declares or decodes to more than `limit` bytes, or
|
||||
/// to a size other than the one its header declares.
|
||||
pub fn unzip_first_entry(zip: &[u8], limit: usize) -> Option<Vec<u8>> {
|
||||
if zip.len() < 30 || read_u32(zip, 0)? != 0x0403_4b50 {
|
||||
return None;
|
||||
}
|
||||
let flags = read_u16(zip, 6)?;
|
||||
let method = read_u16(zip, 8)?;
|
||||
let comp_size = read_u32(zip, 18)? as usize;
|
||||
let uncomp_size = read_u32(zip, 22)? as usize;
|
||||
let name_len = read_u16(zip, 26)? as usize;
|
||||
let extra_len = read_u16(zip, 28)? as usize;
|
||||
|
||||
if (flags & 0x08) != 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let data_off = 30usize.checked_add(name_len)?.checked_add(extra_len)?;
|
||||
if data_off.checked_add(comp_size)? > zip.len() {
|
||||
return None;
|
||||
}
|
||||
if uncomp_size > limit {
|
||||
return None;
|
||||
}
|
||||
let data = &zip[data_off..data_off + comp_size];
|
||||
|
||||
let out = match method {
|
||||
0 => data.to_vec(),
|
||||
8 => {
|
||||
let mut out = Vec::with_capacity(uncomp_size);
|
||||
DeflateDecoder::new(data)
|
||||
.take(uncomp_size as u64 + 1)
|
||||
.read_to_end(&mut out)
|
||||
.ok()?;
|
||||
out
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
(out.len() == uncomp_size).then_some(out)
|
||||
}
|
||||
|
||||
/// Gunzip; pass through already-inflated bytes (edge caches may decompress). Gzip data that does
|
||||
/// not decode, or decodes to more than `limit` bytes, is refused.
|
||||
pub fn maybe_gunzip(body: Vec<u8>, limit: usize) -> Option<Vec<u8>> {
|
||||
if body.len() < 2 || body[0] != 0x1f || body[1] != 0x8b {
|
||||
return (body.len() <= limit).then_some(body);
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
GzDecoder::new(&body[..])
|
||||
.take(limit as u64 + 1)
|
||||
.read_to_end(&mut out)
|
||||
.ok()?;
|
||||
(!out.is_empty() && out.len() <= limit).then_some(out)
|
||||
}
|
||||
|
||||
pub fn hex_encode(bytes: &[u8]) -> String {
|
||||
crate::gog::to_hex(bytes)
|
||||
}
|
||||
|
||||
fn preferred_host(server: &CContentServerDirectoryServerInfo) -> Option<&str> {
|
||||
if !server.vhost.is_empty() {
|
||||
Some(&server.vhost)
|
||||
} else if !server.host.is_empty() {
|
||||
Some(&server.host)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn read_u16(buf: &[u8], off: usize) -> Option<u16> {
|
||||
Some(u16::from_le_bytes(buf.get(off..off + 2)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn read_u32(buf: &[u8], off: usize) -> Option<u32> {
|
||||
Some(u32::from_le_bytes(buf.get(off..off + 4)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use flate2::{write::DeflateEncoder, Compression};
|
||||
use std::io::Write;
|
||||
|
||||
#[test]
|
||||
fn extracts_stored_zip_entry() {
|
||||
let zip = zip_with_entry(0, b"manifest bytes");
|
||||
assert_eq!(unzip_first_entry(&zip, 64), Some(b"manifest bytes".to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_deflated_zip_entry() {
|
||||
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
|
||||
encoder.write_all(b"manifest bytes").unwrap();
|
||||
let deflated = encoder.finish().unwrap();
|
||||
let zip = zip_with_compressed_entry(8, &deflated, b"manifest bytes".len() as u32);
|
||||
assert_eq!(unzip_first_entry(&zip, 64), Some(b"manifest bytes".to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_data_descriptor_zip_entry() {
|
||||
let mut zip = zip_with_entry(0, b"x");
|
||||
zip[6] = 0x08;
|
||||
assert_eq!(unzip_first_entry(&zip, 64), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_encodes_lowercase() {
|
||||
assert_eq!(hex_encode(&[0, 1, 0xab, 0xff]), "0001abff");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_http_appinfo_url() {
|
||||
assert_eq!(
|
||||
build_appinfo_url("cache1.steamcontent.com", 601150, &[0xab, 0xcd, 0x01]),
|
||||
"http://cache1.steamcontent.com/appinfo/601150/sha/abcd01.txt.gz"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gunzips_gzip_and_passes_through_plain_vdf() {
|
||||
use flate2::write::GzEncoder;
|
||||
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
|
||||
encoder.write_all(b"\"appinfo\"{}").unwrap();
|
||||
let gz = encoder.finish().unwrap();
|
||||
assert_eq!(maybe_gunzip(gz.clone(), 64).unwrap(), b"\"appinfo\"{}");
|
||||
assert_eq!(maybe_gunzip(b"\"appinfo\"{}".to_vec(), 64).unwrap(), b"\"appinfo\"{}");
|
||||
assert_eq!(maybe_gunzip(gz, 4), None);
|
||||
assert_eq!(maybe_gunzip(vec![0x1f, 0x8b, 0, 0], 64), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_zip_entries_over_the_limit_or_their_declared_size() {
|
||||
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
|
||||
encoder.write_all(&[7u8; 4096]).unwrap();
|
||||
let deflated = encoder.finish().unwrap();
|
||||
assert!(unzip_first_entry(&zip_with_compressed_entry(8, &deflated, 4096), 4096).is_some());
|
||||
assert_eq!(unzip_first_entry(&zip_with_compressed_entry(8, &deflated, 4096), 4095), None);
|
||||
assert_eq!(unzip_first_entry(&zip_with_compressed_entry(8, &deflated, 16), 4096), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_manifest_and_chunk_urls() {
|
||||
let server = CContentServerDirectoryServerInfo {
|
||||
host: "edge.steamcontent.com".into(),
|
||||
vhost: "cdn.example".into(),
|
||||
https_support: "mandatory".into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
build_manifest_url(&server, 100, 200, 300).unwrap(),
|
||||
"https://cdn.example:443/depot/100/manifest/200/5/300"
|
||||
);
|
||||
assert_eq!(
|
||||
build_chunk_url(&server, 100, &[0xab, 0xcd]).unwrap(),
|
||||
"https://cdn.example:443/depot/100/chunk/abcd"
|
||||
);
|
||||
let plain = CContentServerDirectoryServerInfo {
|
||||
host: "cache1.example".into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
build_manifest_url(&plain, 1, 2, 0).unwrap(),
|
||||
"http://cache1.example:80/depot/1/manifest/2/5"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usable_servers_drop_china_empty_and_duplicate_hosts() {
|
||||
let server = |host: &str, vhost: &str, china: bool| CContentServerDirectoryServerInfo {
|
||||
host: host.into(),
|
||||
vhost: vhost.into(),
|
||||
steam_china_only: china,
|
||||
..Default::default()
|
||||
};
|
||||
let list = usable_servers(&[
|
||||
server("a", "", false),
|
||||
server("b", "", true),
|
||||
server("", "", false),
|
||||
server("c", "a", false),
|
||||
server("d", "", false),
|
||||
]);
|
||||
let hosts: Vec<_> = list.iter().map(host_key).collect();
|
||||
assert_eq!(hosts, vec!["a", "d"]);
|
||||
let many: Vec<_> = (0..20)
|
||||
.map(|i| server(&format!("h{i}"), "", false))
|
||||
.collect();
|
||||
assert_eq!(usable_servers(&many).len(), MAX_CDN_HOSTS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_http_status_lengths_and_manifest_zip() {
|
||||
let zip = zip_with_entry(0, b"manifest bytes");
|
||||
let ok = validate_manifest_response(200, zip.clone(), Some(zip.len() as u64));
|
||||
assert!(ok.ok());
|
||||
assert_eq!(ok.raw_manifest, b"manifest bytes");
|
||||
let short = validate_manifest_response(200, zip, Some(999));
|
||||
assert_eq!(short.error, "manifest body truncated (length mismatch)");
|
||||
assert_eq!(
|
||||
validate_manifest_response(404, vec![], None).error,
|
||||
"HTTP status 404"
|
||||
);
|
||||
}
|
||||
|
||||
fn zip_with_entry(method: u16, data: &[u8]) -> Vec<u8> {
|
||||
zip_with_compressed_entry(method, data, data.len() as u32)
|
||||
}
|
||||
|
||||
fn zip_with_compressed_entry(method: u16, data: &[u8], uncomp_size: u32) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
|
||||
out.extend_from_slice(&20u16.to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(&method.to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(&0u32.to_le_bytes());
|
||||
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&uncomp_size.to_le_bytes());
|
||||
out.extend_from_slice(&1u16.to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(b"x");
|
||||
out.extend_from_slice(data);
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,873 @@
|
||||
//! CM session state and message builders: logon with a refresh token, heartbeat, log-off, and the
|
||||
//! requests a download store needs (PICS, depot keys, manifest request codes, CDN server list,
|
||||
//! free licenses). Social, stats, cloud, lobby and ticket messages are not part of this port.
|
||||
|
||||
use crate::steam::cmsg_protobuf_header::{CMsgProtoBufHeader, INVALID_JOB_ID};
|
||||
use crate::steam::crypto::generate_session_key;
|
||||
use crate::steam::emsg::EMsg;
|
||||
use crate::steam::job_manager::JobResult;
|
||||
use crate::steam::pb::ccontentserverdirectory::{
|
||||
CContentServerDirectoryGetManifestRequestCodeRequest,
|
||||
CContentServerDirectoryGetServersForSteamPipeRequest,
|
||||
};
|
||||
use crate::steam::pb::cmsg_client_get_depot_decryption_key::CMsgClientGetDepotDecryptionKey;
|
||||
use crate::steam::pb::cmsg_client_license_list::{CMsgClientLicenseList, License};
|
||||
use crate::steam::pb::cmsg_client_pics::{
|
||||
CMsgClientPICSAccessTokenRequest, CMsgClientPICSProductInfoRequest, PicsAppInfoReq,
|
||||
PicsPackageInfoReq,
|
||||
};
|
||||
use crate::steam::pb::cmsg_client_request_free_license::CMsgClientRequestFreeLicense;
|
||||
use crate::steam::pb::cmsg_clientserver_login::{
|
||||
CMsgClientHeartBeat, CMsgClientHello, CMsgClientLogOff, CMsgClientLogon,
|
||||
CMsgClientLogonResponse,
|
||||
};
|
||||
use crate::steam::proto_envelope::encode_proto_envelope;
|
||||
use flate2::read::{GzDecoder, ZlibDecoder};
|
||||
use std::io::Read;
|
||||
use std::sync::atomic::{AtomicI32, AtomicU32, AtomicU64, AtomicU8, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Sent as `machine_id` in the logon.
|
||||
pub const MACHINE_ID: &[u8] = b"DroidDeck-Steam";
|
||||
const LOGON_PROTOCOL_VERSION: u32 = 65580;
|
||||
const LOGON_CLIENT_OS_TYPE: u32 = 16;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[repr(u8)]
|
||||
pub enum ClientState {
|
||||
Disconnected,
|
||||
Connecting,
|
||||
Connected,
|
||||
LoggedOn,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum InboundAction {
|
||||
DeliverJob(JobResult),
|
||||
Multi,
|
||||
PicsProductInfo,
|
||||
LogonOk,
|
||||
LoggedOff,
|
||||
LicenseList(usize),
|
||||
ClientMessage,
|
||||
Ignored,
|
||||
ParseFailed(&'static str),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct CMsgMultiBody {
|
||||
pub size_unzipped: u32,
|
||||
pub message_body: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct OutboundProtoMessage {
|
||||
pub emsg: EMsg,
|
||||
pub routing_appid: u32,
|
||||
pub body: Vec<u8>,
|
||||
pub wire: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct OutboundServiceCall {
|
||||
pub method_name: String,
|
||||
pub authed: bool,
|
||||
pub job_id: u64,
|
||||
pub request_body: Vec<u8>,
|
||||
pub wire: Vec<u8>,
|
||||
}
|
||||
|
||||
pub struct CMClientCore {
|
||||
state: AtomicU8,
|
||||
steam_id: AtomicU64,
|
||||
session_id: AtomicI32,
|
||||
cell_id: AtomicU32,
|
||||
/// EResult of the last logon response or log-off (0 = none yet).
|
||||
last_logon_eresult: AtomicI32,
|
||||
license_list: Mutex<Option<Vec<License>>>,
|
||||
outbound_wires: Mutex<Vec<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl Default for CMClientCore {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
state: AtomicU8::new(ClientState::Disconnected as u8),
|
||||
steam_id: AtomicU64::new(0),
|
||||
session_id: AtomicI32::new(0),
|
||||
cell_id: AtomicU32::new(0),
|
||||
last_logon_eresult: AtomicI32::new(0),
|
||||
license_list: Mutex::new(None),
|
||||
outbound_wires: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CMClientCore {
|
||||
pub fn state(&self) -> ClientState {
|
||||
match self.state.load(Ordering::Relaxed) {
|
||||
1 => ClientState::Connecting,
|
||||
2 => ClientState::Connected,
|
||||
3 => ClientState::LoggedOn,
|
||||
_ => ClientState::Disconnected,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_state(&self, state: ClientState) {
|
||||
self.state.store(state as u8, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn reset_session_identity(&self) {
|
||||
self.steam_id.store(0, Ordering::Relaxed);
|
||||
self.session_id.store(0, Ordering::Relaxed);
|
||||
// Unsent wires can hold the logon token.
|
||||
let mut queue = self.outbound_wires.lock().expect("outbound queue poisoned");
|
||||
for wire in queue.iter_mut() {
|
||||
zeroize::Zeroize::zeroize(wire);
|
||||
}
|
||||
queue.clear();
|
||||
}
|
||||
|
||||
pub fn steam_id(&self) -> u64 {
|
||||
self.steam_id.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn session_id(&self) -> i32 {
|
||||
self.session_id.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn cell_id(&self) -> u32 {
|
||||
self.cell_id.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn last_logon_eresult(&self) -> i32 {
|
||||
self.last_logon_eresult.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn clear_last_logon_eresult(&self) {
|
||||
self.last_logon_eresult.store(0, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The license list Steam pushed after logon; `None` until it arrived.
|
||||
pub fn license_list(&self) -> Option<Vec<License>> {
|
||||
self.license_list
|
||||
.lock()
|
||||
.expect("license list poisoned")
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub fn enqueue_proto_message(&self, message: Option<OutboundProtoMessage>) -> bool {
|
||||
let Some(message) = message else {
|
||||
return false;
|
||||
};
|
||||
self.enqueue_wire(message.wire)
|
||||
}
|
||||
|
||||
pub fn enqueue_wire(&self, wire: Vec<u8>) -> bool {
|
||||
if wire.is_empty() {
|
||||
return false;
|
||||
}
|
||||
self.outbound_wires
|
||||
.lock()
|
||||
.expect("outbound queue poisoned")
|
||||
.push(wire);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn restore_outbound_wires_front(&self, mut wires: Vec<Vec<u8>>) {
|
||||
if wires.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut queue = self.outbound_wires.lock().expect("outbound queue poisoned");
|
||||
if queue.is_empty() {
|
||||
*queue = wires;
|
||||
return;
|
||||
}
|
||||
let mut restored = Vec::with_capacity(wires.len() + queue.len());
|
||||
restored.append(&mut wires);
|
||||
restored.append(&mut queue);
|
||||
*queue = restored;
|
||||
}
|
||||
|
||||
pub fn take_outbound_wires(&self) -> Vec<Vec<u8>> {
|
||||
std::mem::take(&mut *self.outbound_wires.lock().expect("outbound queue poisoned"))
|
||||
}
|
||||
|
||||
pub fn build_proto_message(&self, emsg: EMsg, body: &[u8], routing_appid: u32) -> Vec<u8> {
|
||||
let mut header = CMsgProtoBufHeader {
|
||||
steamid: self.steam_id(),
|
||||
client_sessionid: self.session_id(),
|
||||
routing_appid,
|
||||
..Default::default()
|
||||
};
|
||||
if emsg == EMsg::CLIENT_LOGON && header.steamid == 0 {
|
||||
header.steamid = 0x0110_0001_0000_0000;
|
||||
}
|
||||
encode_proto_envelope(emsg, &header, body)
|
||||
}
|
||||
|
||||
pub fn build_client_hello(&self) -> OutboundProtoMessage {
|
||||
let body = CMsgClientHello::default().serialize();
|
||||
let wire = self.build_proto_message(EMsg::CLIENT_HELLO, &body, 0);
|
||||
OutboundProtoMessage {
|
||||
emsg: EMsg::CLIENT_HELLO,
|
||||
routing_appid: 0,
|
||||
body,
|
||||
wire,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_heartbeat(&self) -> OutboundProtoMessage {
|
||||
let body = CMsgClientHeartBeat::default().serialize();
|
||||
let wire = self.build_proto_message(EMsg::CLIENT_HEART_BEAT, &body, 0);
|
||||
OutboundProtoMessage {
|
||||
emsg: EMsg::CLIENT_HEART_BEAT,
|
||||
routing_appid: 0,
|
||||
body,
|
||||
wire,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_logoff(&self) -> Option<OutboundProtoMessage> {
|
||||
if self.state() != ClientState::LoggedOn {
|
||||
return None;
|
||||
}
|
||||
self.build_outbound_proto_message(EMsg::CLIENT_LOG_OFF, CMsgClientLogOff.serialize(), 0)
|
||||
}
|
||||
|
||||
/// `ClientLogon` carrying the saved refresh token as `access_token`. The returned wire holds
|
||||
/// the token; drop it as soon as it is queued.
|
||||
pub fn build_logon_with_refresh_token(
|
||||
&self,
|
||||
refresh_token: &str,
|
||||
account_name: &str,
|
||||
client_supplied_steam_id: u64,
|
||||
) -> Option<OutboundProtoMessage> {
|
||||
if self.state() != ClientState::Connected || refresh_token.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut msg = CMsgClientLogon {
|
||||
access_token: refresh_token.to_string(),
|
||||
account_name: account_name.to_string(),
|
||||
client_supplied_steam_id,
|
||||
machine_id: MACHINE_ID.to_vec(),
|
||||
protocol_version: LOGON_PROTOCOL_VERSION,
|
||||
client_os_type: LOGON_CLIENT_OS_TYPE,
|
||||
supports_rate_limit_response: true,
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(key) = generate_session_key() {
|
||||
let mut client_instance_id = 0u64;
|
||||
for (idx, byte) in key.bytes.iter().take(8).enumerate() {
|
||||
client_instance_id |= (*byte as u64) << (idx * 8);
|
||||
}
|
||||
msg.client_instance_id = client_instance_id.max(1);
|
||||
let mut login_id = 0u32;
|
||||
for (idx, byte) in key.bytes.iter().skip(8).take(4).enumerate() {
|
||||
login_id |= (*byte as u32) << (idx * 8);
|
||||
}
|
||||
msg.obfuscated_private_ip = login_id.max(1);
|
||||
}
|
||||
let body = msg.serialize();
|
||||
zeroize::Zeroize::zeroize(&mut msg.access_token);
|
||||
let wire = self.build_proto_message(EMsg::CLIENT_LOGON, &body, 0);
|
||||
let mut body = body;
|
||||
zeroize::Zeroize::zeroize(&mut body);
|
||||
Some(OutboundProtoMessage {
|
||||
emsg: EMsg::CLIENT_LOGON,
|
||||
routing_appid: 0,
|
||||
body: Vec::new(),
|
||||
wire,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_service_method_call(
|
||||
&self,
|
||||
method_name: &str,
|
||||
authed: bool,
|
||||
job_id: u64,
|
||||
request_body: &[u8],
|
||||
) -> Vec<u8> {
|
||||
let header = CMsgProtoBufHeader {
|
||||
steamid: self.steam_id(),
|
||||
client_sessionid: self.session_id(),
|
||||
jobid_source: job_id,
|
||||
jobid_target: INVALID_JOB_ID,
|
||||
target_job_name: method_name.to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
let emsg = if authed {
|
||||
EMsg::SERVICE_METHOD_CALL_FROM_CLIENT
|
||||
} else {
|
||||
EMsg::SERVICE_METHOD_CALL_FROM_CLIENT_NON_AUTHED
|
||||
};
|
||||
encode_proto_envelope(emsg, &header, request_body)
|
||||
}
|
||||
|
||||
pub fn build_outbound_proto_message(
|
||||
&self,
|
||||
emsg: EMsg,
|
||||
body: Vec<u8>,
|
||||
routing_appid: u32,
|
||||
) -> Option<OutboundProtoMessage> {
|
||||
if self.state() != ClientState::LoggedOn {
|
||||
return None;
|
||||
}
|
||||
let wire = self.build_proto_message(emsg, &body, routing_appid);
|
||||
Some(OutboundProtoMessage {
|
||||
emsg,
|
||||
routing_appid,
|
||||
body,
|
||||
wire,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_job_proto_message(
|
||||
&self,
|
||||
emsg: EMsg,
|
||||
job_id: u64,
|
||||
body: Vec<u8>,
|
||||
routing_appid: u32,
|
||||
) -> Option<OutboundProtoMessage> {
|
||||
if self.state() != ClientState::LoggedOn {
|
||||
return None;
|
||||
}
|
||||
let header = CMsgProtoBufHeader {
|
||||
steamid: self.steam_id(),
|
||||
client_sessionid: self.session_id(),
|
||||
routing_appid,
|
||||
jobid_source: job_id,
|
||||
jobid_target: INVALID_JOB_ID,
|
||||
..Default::default()
|
||||
};
|
||||
let wire = encode_proto_envelope(emsg, &header, &body);
|
||||
Some(OutboundProtoMessage {
|
||||
emsg,
|
||||
routing_appid,
|
||||
body,
|
||||
wire,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_authed_service_call(
|
||||
&self,
|
||||
method_name: &str,
|
||||
job_id: u64,
|
||||
request_body: Vec<u8>,
|
||||
) -> Option<OutboundServiceCall> {
|
||||
if self.state() != ClientState::LoggedOn {
|
||||
return None;
|
||||
}
|
||||
let wire = self.build_service_method_call(method_name, true, job_id, &request_body);
|
||||
Some(OutboundServiceCall {
|
||||
method_name: method_name.to_string(),
|
||||
authed: true,
|
||||
job_id,
|
||||
request_body,
|
||||
wire,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_get_depot_decryption_key(
|
||||
&self,
|
||||
depot_id: u32,
|
||||
app_id: u32,
|
||||
job_id: u64,
|
||||
) -> Option<OutboundProtoMessage> {
|
||||
if depot_id == 0 || app_id == 0 {
|
||||
return None;
|
||||
}
|
||||
self.build_job_proto_message(
|
||||
EMsg::CLIENT_GET_DEPOT_DECRYPTION_KEY,
|
||||
job_id,
|
||||
CMsgClientGetDepotDecryptionKey { depot_id, app_id }.serialize(),
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn build_manifest_request_code_call(
|
||||
&self,
|
||||
app_id: u32,
|
||||
depot_id: u32,
|
||||
manifest_id: u64,
|
||||
branch: &str,
|
||||
job_id: u64,
|
||||
) -> Option<OutboundServiceCall> {
|
||||
if app_id == 0 || depot_id == 0 || manifest_id == 0 {
|
||||
return None;
|
||||
}
|
||||
let lower = branch.to_ascii_lowercase();
|
||||
let app_branch = if lower.is_empty() || lower == "public" {
|
||||
String::new()
|
||||
} else {
|
||||
branch.to_string()
|
||||
};
|
||||
self.build_authed_service_call(
|
||||
"ContentServerDirectory.GetManifestRequestCode#1",
|
||||
job_id,
|
||||
CContentServerDirectoryGetManifestRequestCodeRequest {
|
||||
app_id,
|
||||
depot_id,
|
||||
manifest_id,
|
||||
app_branch,
|
||||
branch_password_hash: String::new(),
|
||||
}
|
||||
.serialize(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn build_get_cdn_servers_call(
|
||||
&self,
|
||||
cell_id: u32,
|
||||
job_id: u64,
|
||||
) -> Option<OutboundServiceCall> {
|
||||
self.build_authed_service_call(
|
||||
"ContentServerDirectory.GetServersForSteamPipe#1",
|
||||
job_id,
|
||||
CContentServerDirectoryGetServersForSteamPipeRequest {
|
||||
cell_id,
|
||||
..Default::default()
|
||||
}
|
||||
.serialize(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn build_pics_access_tokens(
|
||||
&self,
|
||||
packageids: Vec<u32>,
|
||||
appids: Vec<u32>,
|
||||
job_id: u64,
|
||||
) -> Option<OutboundProtoMessage> {
|
||||
self.build_job_proto_message(
|
||||
EMsg::CLIENT_PICS_ACCESS_TOKEN_REQUEST,
|
||||
job_id,
|
||||
CMsgClientPICSAccessTokenRequest { packageids, appids }.serialize(),
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn build_pics_product_info(
|
||||
&self,
|
||||
packages: Vec<PicsPackageInfoReq>,
|
||||
apps: Vec<PicsAppInfoReq>,
|
||||
meta_data_only: bool,
|
||||
job_id: u64,
|
||||
) -> Option<OutboundProtoMessage> {
|
||||
self.build_job_proto_message(
|
||||
EMsg::CLIENT_PICS_PRODUCT_INFO_REQUEST,
|
||||
job_id,
|
||||
CMsgClientPICSProductInfoRequest {
|
||||
packages,
|
||||
apps,
|
||||
meta_data_only,
|
||||
single_response: false,
|
||||
..Default::default()
|
||||
}
|
||||
.serialize(),
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
/// Succeeds only for apps Steam gives away; a paid unowned app comes back with a non-OK
|
||||
/// EResult in the response body.
|
||||
pub fn build_request_free_license(
|
||||
&self,
|
||||
app_ids: &[u32],
|
||||
job_id: u64,
|
||||
) -> Option<OutboundProtoMessage> {
|
||||
if app_ids.is_empty() {
|
||||
return None;
|
||||
}
|
||||
self.build_job_proto_message(
|
||||
EMsg::CLIENT_REQUEST_FREE_LICENSE,
|
||||
job_id,
|
||||
CMsgClientRequestFreeLicense {
|
||||
appids: app_ids.to_vec(),
|
||||
}
|
||||
.serialize(),
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn route_inbound(
|
||||
&self,
|
||||
emsg: EMsg,
|
||||
header: &CMsgProtoBufHeader,
|
||||
body: &[u8],
|
||||
) -> InboundAction {
|
||||
match emsg {
|
||||
EMsg::SERVICE_METHOD_RESPONSE
|
||||
| EMsg::CLIENT_PICS_ACCESS_TOKEN_RESPONSE
|
||||
| EMsg::CLIENT_GET_DEPOT_DECRYPTION_KEY_RESPONSE
|
||||
// 5573 carries its own EResult in the body; the job only reports transport health.
|
||||
| EMsg::CLIENT_REQUEST_FREE_LICENSE_RESPONSE => {
|
||||
if header.jobid_target == INVALID_JOB_ID {
|
||||
InboundAction::Ignored
|
||||
} else {
|
||||
let eresult = if header.eresult == -1 {
|
||||
1
|
||||
} else {
|
||||
header.eresult
|
||||
};
|
||||
InboundAction::DeliverJob(JobResult {
|
||||
eresult,
|
||||
error_message: header.error_message.clone(),
|
||||
body: body.to_vec(),
|
||||
synthetic_failure: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
EMsg::CLIENT_PICS_PRODUCT_INFO_RESPONSE => InboundAction::PicsProductInfo,
|
||||
EMsg::MULTI => InboundAction::Multi,
|
||||
EMsg::CLIENT_LOGON_RESPONSE => {
|
||||
let Some(resp) = CMsgClientLogonResponse::deserialize(body) else {
|
||||
return InboundAction::ParseFailed("ClientLogonResponse");
|
||||
};
|
||||
// The eresult is published last (Release) so a waiter that sees it also sees the
|
||||
// state and ids that go with it.
|
||||
let action = if resp.eresult == 1 {
|
||||
self.state
|
||||
.store(ClientState::LoggedOn as u8, Ordering::Relaxed);
|
||||
self.steam_id
|
||||
.store(resp.client_supplied_steamid, Ordering::Relaxed);
|
||||
self.session_id
|
||||
.store(header.client_sessionid, Ordering::Relaxed);
|
||||
self.cell_id.store(resp.cell_id, Ordering::Relaxed);
|
||||
InboundAction::LogonOk
|
||||
} else {
|
||||
InboundAction::LoggedOff
|
||||
};
|
||||
self.last_logon_eresult
|
||||
.store(resp.eresult, Ordering::Release);
|
||||
action
|
||||
}
|
||||
EMsg::CLIENT_LOGGED_OFF | EMsg::CLIENT_SERVER_UNAVAILABLE => {
|
||||
if self.state() == ClientState::LoggedOn {
|
||||
self.state
|
||||
.store(ClientState::Connected as u8, Ordering::Relaxed);
|
||||
}
|
||||
if emsg == EMsg::CLIENT_LOGGED_OFF {
|
||||
let eresult = crate::steam::pb::cmsg_clientserver_login::CMsgClientLoggedOff::deserialize(body)
|
||||
.map(|m| m.eresult)
|
||||
.unwrap_or(2);
|
||||
self.last_logon_eresult.store(eresult, Ordering::Relaxed);
|
||||
}
|
||||
self.steam_id.store(0, Ordering::Relaxed);
|
||||
self.session_id.store(0, Ordering::Relaxed);
|
||||
InboundAction::LoggedOff
|
||||
}
|
||||
EMsg::CLIENT_LICENSE_LIST => {
|
||||
let Some(msg) = CMsgClientLicenseList::deserialize(body) else {
|
||||
return InboundAction::ParseFailed("ClientLicenseList");
|
||||
};
|
||||
let count = msg.licenses.len();
|
||||
// A refused list keeps the last good snapshot (or none, so the load reports it).
|
||||
if msg.eresult != 1 && msg.licenses.is_empty() {
|
||||
return InboundAction::ParseFailed("ClientLicenseList refused");
|
||||
}
|
||||
*self.license_list.lock().expect("license list poisoned") = Some(msg.licenses);
|
||||
InboundAction::LicenseList(count)
|
||||
}
|
||||
_ => InboundAction::ClientMessage,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_cmsg_multi(body: &[u8]) -> Option<CMsgMultiBody> {
|
||||
let mut reader = crate::steam::proto_wire::Reader::new(body);
|
||||
let mut multi = CMsgMultiBody::default();
|
||||
while !reader.eof() {
|
||||
let Some(tag) = reader.next_tag() else {
|
||||
return reader.ok().then_some(multi);
|
||||
};
|
||||
match tag.field_number {
|
||||
1 => multi.size_unzipped = reader.u32()?,
|
||||
2 => multi.message_body = reader.bytes()?.to_vec(),
|
||||
_ => {
|
||||
if !reader.skip(tag.wire_type) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(multi)
|
||||
}
|
||||
|
||||
pub fn decode_multi_records(body: &[u8]) -> Option<Vec<Vec<u8>>> {
|
||||
let multi = parse_cmsg_multi(body)?;
|
||||
let records = if multi.size_unzipped > 0 {
|
||||
gunzip_or_zlib(&multi.message_body, multi.size_unzipped as usize)?
|
||||
} else {
|
||||
multi.message_body
|
||||
};
|
||||
|
||||
let mut out = Vec::new();
|
||||
let mut offset = 0usize;
|
||||
while offset + 4 <= records.len() {
|
||||
let inner_len = crate::steam::wire_format::read_u32_le(&records[offset..]) as usize;
|
||||
offset += 4;
|
||||
if inner_len == 0 || offset + inner_len > records.len() {
|
||||
return None;
|
||||
}
|
||||
out.push(records[offset..offset + inner_len].to_vec());
|
||||
offset += inner_len;
|
||||
}
|
||||
(offset == records.len()).then_some(out)
|
||||
}
|
||||
|
||||
/// Largest MULTI batch accepted once decompressed.
|
||||
const MAX_MULTI_UNZIPPED: usize = 64 << 20;
|
||||
|
||||
fn gunzip_or_zlib(compressed: &[u8], expected_size: usize) -> Option<Vec<u8>> {
|
||||
if expected_size == 0 || expected_size > MAX_MULTI_UNZIPPED {
|
||||
return None;
|
||||
}
|
||||
let limit = expected_size as u64 + 1;
|
||||
let mut out = Vec::with_capacity(expected_size);
|
||||
if GzDecoder::new(compressed).take(limit).read_to_end(&mut out).is_ok() && out.len() == expected_size {
|
||||
return Some(out);
|
||||
}
|
||||
out.clear();
|
||||
if ZlibDecoder::new(compressed).take(limit).read_to_end(&mut out).is_ok() && out.len() == expected_size {
|
||||
return Some(out);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::steam::proto_envelope::decode_proto_envelope;
|
||||
use crate::steam::proto_wire::{WireType, Writer};
|
||||
use flate2::write::GzEncoder;
|
||||
use flate2::Compression;
|
||||
use std::io::Write;
|
||||
|
||||
#[test]
|
||||
fn service_method_call_sets_authed_and_non_authed_emsgs() {
|
||||
let core = CMClientCore::default();
|
||||
core.steam_id.store(123, Ordering::Relaxed);
|
||||
core.session_id.store(7, Ordering::Relaxed);
|
||||
let authed = decode_proto_envelope(&core.build_service_method_call(
|
||||
"ContentServerDirectory.GetServersForSteamPipe#1",
|
||||
true,
|
||||
55,
|
||||
b"req",
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(authed.emsg, EMsg::SERVICE_METHOD_CALL_FROM_CLIENT);
|
||||
assert_eq!(authed.header.steamid, 123);
|
||||
assert_eq!(authed.header.client_sessionid, 7);
|
||||
assert_eq!(authed.header.jobid_source, 55);
|
||||
assert_eq!(authed.body, b"req");
|
||||
let non = decode_proto_envelope(&core.build_service_method_call("X.Y#1", false, 56, b""))
|
||||
.unwrap();
|
||||
assert_eq!(non.emsg, EMsg::SERVICE_METHOD_CALL_FROM_CLIENT_NON_AUTHED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmsg_multi_decodes_plain_and_gzip_records() {
|
||||
let first = encode_proto_envelope(EMsg::CLIENT_HELLO, &CMsgProtoBufHeader::default(), b"a");
|
||||
let second = encode_proto_envelope(
|
||||
EMsg::CLIENT_LICENSE_LIST,
|
||||
&CMsgProtoBufHeader::default(),
|
||||
b"b",
|
||||
);
|
||||
let mut records = Vec::new();
|
||||
records.extend_from_slice(&(first.len() as u32).to_le_bytes());
|
||||
records.extend_from_slice(&first);
|
||||
records.extend_from_slice(&(second.len() as u32).to_le_bytes());
|
||||
records.extend_from_slice(&second);
|
||||
|
||||
let mut body = Vec::new();
|
||||
Writer::new(&mut body).bytes_field(2, &records);
|
||||
assert_eq!(
|
||||
decode_multi_records(&body).unwrap(),
|
||||
vec![first.clone(), second.clone()]
|
||||
);
|
||||
|
||||
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
|
||||
encoder.write_all(&records).unwrap();
|
||||
let zipped = encoder.finish().unwrap();
|
||||
let mut zipped_body = Vec::new();
|
||||
{
|
||||
let mut writer = Writer::new(&mut zipped_body);
|
||||
writer.uint32_field(1, records.len() as u32);
|
||||
writer.bytes_field(2, &zipped);
|
||||
}
|
||||
assert_eq!(
|
||||
decode_multi_records(&zipped_body).unwrap(),
|
||||
vec![first, second]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logon_needs_connected_state_and_carries_token_and_machine_id() {
|
||||
let core = CMClientCore::default();
|
||||
assert!(core
|
||||
.build_logon_with_refresh_token("refresh", "ada", 0)
|
||||
.is_none());
|
||||
core.set_state(ClientState::Connected);
|
||||
let logon = core
|
||||
.build_logon_with_refresh_token("refresh", "ada", 123)
|
||||
.unwrap();
|
||||
assert_eq!(logon.emsg, EMsg::CLIENT_LOGON);
|
||||
let decoded = decode_proto_envelope(&logon.wire).unwrap();
|
||||
assert_eq!(decoded.header.steamid, 0x0110_0001_0000_0000);
|
||||
assert!(decoded.body.windows(7).any(|w| w == b"refresh"));
|
||||
assert!(decoded
|
||||
.body
|
||||
.windows(MACHINE_ID.len())
|
||||
.any(|w| w == MACHINE_ID));
|
||||
assert!(logon.body.is_empty());
|
||||
assert!(core.build_logon_with_refresh_token("", "ada", 1).is_none());
|
||||
|
||||
assert!(core.build_logoff().is_none());
|
||||
core.set_state(ClientState::LoggedOn);
|
||||
assert_eq!(core.build_logoff().unwrap().emsg, EMsg::CLIENT_LOG_OFF);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logon_response_updates_session_identity_and_eresult() {
|
||||
let core = CMClientCore::default();
|
||||
let mut body = Vec::new();
|
||||
{
|
||||
let mut w = Writer::new(&mut body);
|
||||
w.int32_field(1, 1);
|
||||
w.tag(20, WireType::Fixed64);
|
||||
w.raw_bytes(&765u64.to_le_bytes());
|
||||
}
|
||||
let header = CMsgProtoBufHeader {
|
||||
client_sessionid: 42,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
core.route_inbound(EMsg::CLIENT_LOGON_RESPONSE, &header, &body),
|
||||
InboundAction::LogonOk
|
||||
);
|
||||
assert_eq!(core.state(), ClientState::LoggedOn);
|
||||
assert_eq!(core.steam_id(), 765);
|
||||
assert_eq!(core.session_id(), 42);
|
||||
assert_eq!(core.last_logon_eresult(), 1);
|
||||
|
||||
assert_eq!(
|
||||
core.route_inbound(EMsg::CLIENT_LOGGED_OFF, &CMsgProtoBufHeader::default(), &[]),
|
||||
InboundAction::LoggedOff
|
||||
);
|
||||
assert_eq!(core.state(), ClientState::Connected);
|
||||
assert_eq!(core.steam_id(), 0);
|
||||
|
||||
let mut refused = Vec::new();
|
||||
Writer::new(&mut refused).int32_field(1, 5);
|
||||
let fresh = CMClientCore::default();
|
||||
assert_eq!(
|
||||
fresh.route_inbound(EMsg::CLIENT_LOGON_RESPONSE, &header, &refused),
|
||||
InboundAction::LoggedOff
|
||||
);
|
||||
assert_eq!(fresh.last_logon_eresult(), 5);
|
||||
assert_eq!(fresh.state(), ClientState::Disconnected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn license_list_push_is_stored() {
|
||||
let core = CMClientCore::default();
|
||||
assert!(core.license_list().is_none());
|
||||
let mut refused = Vec::new();
|
||||
Writer::new(&mut refused).int32_field(1, 2);
|
||||
assert!(matches!(
|
||||
core.route_inbound(EMsg::CLIENT_LICENSE_LIST, &CMsgProtoBufHeader::default(), &refused),
|
||||
InboundAction::ParseFailed(_)
|
||||
));
|
||||
assert!(core.license_list().is_none());
|
||||
let mut ok = Vec::new();
|
||||
Writer::new(&mut ok).int32_field(1, 1);
|
||||
assert_eq!(
|
||||
core.route_inbound(EMsg::CLIENT_LICENSE_LIST, &CMsgProtoBufHeader::default(), &ok),
|
||||
InboundAction::LicenseList(0)
|
||||
);
|
||||
assert_eq!(core.license_list(), Some(Vec::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn downloader_builders_use_the_expected_messages() {
|
||||
let core = logged_on_core();
|
||||
let depot_key = core.build_get_depot_decryption_key(11, 22, 33).unwrap();
|
||||
let decoded = decode_proto_envelope(&depot_key.wire).unwrap();
|
||||
assert_eq!(decoded.emsg, EMsg::CLIENT_GET_DEPOT_DECRYPTION_KEY);
|
||||
assert_eq!(decoded.header.jobid_source, 33);
|
||||
|
||||
let public = core
|
||||
.build_manifest_request_code_call(480, 100, 555, "public", 44)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
public.method_name,
|
||||
"ContentServerDirectory.GetManifestRequestCode#1"
|
||||
);
|
||||
assert!(!public.request_body.windows(6).any(|w| w == b"public"));
|
||||
let beta = core
|
||||
.build_manifest_request_code_call(480, 100, 555, "Beta", 45)
|
||||
.unwrap();
|
||||
assert!(beta.request_body.windows(4).any(|w| w == b"Beta"));
|
||||
|
||||
let servers = core.build_get_cdn_servers_call(7, 46).unwrap();
|
||||
assert_eq!(
|
||||
servers.method_name,
|
||||
"ContentServerDirectory.GetServersForSteamPipe#1"
|
||||
);
|
||||
|
||||
let product = core
|
||||
.build_pics_product_info(
|
||||
vec![PicsPackageInfoReq {
|
||||
packageid: 100,
|
||||
access_token: 7,
|
||||
}],
|
||||
vec![PicsAppInfoReq {
|
||||
appid: 480,
|
||||
access_token: 8,
|
||||
only_public_obsolete: false,
|
||||
}],
|
||||
true,
|
||||
3,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(product.emsg, EMsg::CLIENT_PICS_PRODUCT_INFO_REQUEST);
|
||||
assert!(product.body.windows(2).any(|w| w == [0x18, 1]));
|
||||
|
||||
let free = core.build_request_free_license(&[440], 50).unwrap();
|
||||
assert_eq!(free.emsg, EMsg::CLIENT_REQUEST_FREE_LICENSE);
|
||||
assert_eq!(free.body, [0x10, 0xb8, 0x03]);
|
||||
assert!(core.build_request_free_license(&[], 51).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn job_responses_are_delivered_and_builders_need_logon() {
|
||||
let core = logged_on_core();
|
||||
let header = CMsgProtoBufHeader {
|
||||
jobid_target: 50,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
core.route_inbound(EMsg::CLIENT_REQUEST_FREE_LICENSE_RESPONSE, &header, &[]),
|
||||
InboundAction::DeliverJob(_)
|
||||
));
|
||||
assert_eq!(
|
||||
core.route_inbound(
|
||||
EMsg::SERVICE_METHOD_RESPONSE,
|
||||
&CMsgProtoBufHeader::default(),
|
||||
&[]
|
||||
),
|
||||
InboundAction::Ignored
|
||||
);
|
||||
let offline = CMClientCore::default();
|
||||
assert!(offline.build_get_depot_decryption_key(1, 2, 3).is_none());
|
||||
assert!(offline.build_get_cdn_servers_call(0, 1).is_none());
|
||||
}
|
||||
|
||||
fn logged_on_core() -> CMClientCore {
|
||||
let core = CMClientCore::default();
|
||||
core.state
|
||||
.store(ClientState::LoggedOn as u8, Ordering::Relaxed);
|
||||
core.steam_id.store(7656119, Ordering::Relaxed);
|
||||
core.session_id.store(42, Ordering::Relaxed);
|
||||
core
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
use crate::steam::cm_client::{decode_multi_records, CMClientCore, ClientState, InboundAction};
|
||||
use crate::steam::cmsg_protobuf_header::{CMsgProtoBufHeader, INVALID_JOB_ID};
|
||||
use crate::steam::emsg::{has_proto_flag, strip_proto_flag, EMsg};
|
||||
use crate::steam::encrypted_channel::{ChannelDisconnectReason, ChannelState, EncryptedChannel};
|
||||
use crate::steam::heartbeat::Heartbeat;
|
||||
use crate::steam::job_manager::{JobManager, JobResult};
|
||||
use crate::steam::pb::cmsg_client_pics::CMsgClientPICSProductInfoResponse;
|
||||
use crate::steam::pb::cmsg_clientserver_login::CMsgClientLogonResponse;
|
||||
use crate::steam::proto_envelope::decode_proto_envelope;
|
||||
use crate::steam::transport::Transport;
|
||||
use crate::steam::wire_format::read_u32_le;
|
||||
use std::collections::HashMap;
|
||||
use std::panic::{self, AssertUnwindSafe};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
type StateCallback = Box<dyn Fn(ClientState) + Send + Sync + 'static>;
|
||||
type ClientMessageCallback = Box<dyn Fn(EMsg, &CMsgProtoBufHeader, &[u8]) + Send + Sync + 'static>;
|
||||
|
||||
/// MULTI batches nest at most this deep (Steam sends one level).
|
||||
const MAX_MULTI_DEPTH: u32 = 2;
|
||||
|
||||
pub struct CMClientRuntime {
|
||||
flush: Mutex<()>,
|
||||
core: Arc<CMClientCore>,
|
||||
channel: EncryptedChannel,
|
||||
jobs: JobManager,
|
||||
heartbeat: Mutex<Heartbeat>,
|
||||
pics_product_info: Mutex<HashMap<u64, CMsgClientPICSProductInfoResponse>>,
|
||||
on_state: Mutex<Option<StateCallback>>,
|
||||
on_client_message: Mutex<Option<ClientMessageCallback>>,
|
||||
}
|
||||
|
||||
impl CMClientRuntime {
|
||||
pub fn new(core: Arc<CMClientCore>, transport: Box<dyn Transport>) -> Arc<Self> {
|
||||
let runtime = Arc::new(Self {
|
||||
flush: Mutex::new(()),
|
||||
core,
|
||||
channel: EncryptedChannel::new(transport),
|
||||
jobs: JobManager::default(),
|
||||
heartbeat: Mutex::new(Heartbeat::default()),
|
||||
pics_product_info: Mutex::new(HashMap::new()),
|
||||
on_state: Mutex::new(None),
|
||||
on_client_message: Mutex::new(None),
|
||||
});
|
||||
|
||||
let weak = Arc::downgrade(&runtime);
|
||||
runtime.channel.set_on_connected(move || {
|
||||
if let Some(runtime) = weak.upgrade() {
|
||||
runtime.on_channel_connected();
|
||||
}
|
||||
});
|
||||
|
||||
let weak = Arc::downgrade(&runtime);
|
||||
runtime.channel.set_on_disconnected(move |reason, detail| {
|
||||
if let Some(runtime) = weak.upgrade() {
|
||||
runtime.on_channel_disconnected(reason, detail);
|
||||
}
|
||||
});
|
||||
|
||||
let weak = Arc::downgrade(&runtime);
|
||||
runtime.channel.set_on_message(move |bytes| {
|
||||
if let Some(runtime) = weak.upgrade() {
|
||||
runtime.handle_channel_message(bytes);
|
||||
}
|
||||
});
|
||||
|
||||
runtime
|
||||
}
|
||||
|
||||
pub fn core(&self) -> &Arc<CMClientCore> {
|
||||
&self.core
|
||||
}
|
||||
|
||||
pub fn connect(&self, url: &str) -> bool {
|
||||
self.core.set_state(ClientState::Connecting);
|
||||
self.notify_state(ClientState::Connecting);
|
||||
if self.channel.connect(url) {
|
||||
true
|
||||
} else {
|
||||
self.core.set_state(ClientState::Disconnected);
|
||||
self.notify_state(ClientState::Disconnected);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn disconnect(&self) {
|
||||
self.heartbeat.lock().expect("heartbeat poisoned").stop();
|
||||
self.channel.disconnect();
|
||||
self.jobs.fail_all("CMClient disconnected");
|
||||
self.core.reset_session_identity();
|
||||
self.core.set_state(ClientState::Disconnected);
|
||||
self.notify_state(ClientState::Disconnected);
|
||||
}
|
||||
|
||||
pub fn set_ca_bundle_path(&self, path: &str) {
|
||||
self.channel.set_ca_bundle_path(path);
|
||||
}
|
||||
|
||||
pub fn set_on_state<F>(&self, callback: F)
|
||||
where
|
||||
F: Fn(ClientState) + Send + Sync + 'static,
|
||||
{
|
||||
*self.on_state.lock().expect("runtime callback poisoned") = Some(Box::new(callback));
|
||||
}
|
||||
|
||||
pub fn set_on_client_message<F>(&self, callback: F)
|
||||
where
|
||||
F: Fn(EMsg, &CMsgProtoBufHeader, &[u8]) + Send + Sync + 'static,
|
||||
{
|
||||
*self
|
||||
.on_client_message
|
||||
.lock()
|
||||
.expect("runtime callback poisoned") = Some(Box::new(callback));
|
||||
}
|
||||
|
||||
pub fn next_job_id(&self) -> u64 {
|
||||
self.jobs.next_job_id()
|
||||
}
|
||||
|
||||
pub fn track_job<F>(&self, job_id: u64, callback: F, timeout: Option<Duration>)
|
||||
where
|
||||
F: FnOnce(JobResult) + Send + 'static,
|
||||
{
|
||||
self.jobs.track(job_id, callback, timeout);
|
||||
}
|
||||
|
||||
pub fn flush_outbound(&self) -> usize {
|
||||
if self.channel.state() != ChannelState::Encrypted {
|
||||
return 0;
|
||||
}
|
||||
// One flush at a time, so two flushers cannot send queued wires out of order.
|
||||
let _flushing = self.flush.lock().expect("flush poisoned");
|
||||
let mut wires = self.core.take_outbound_wires();
|
||||
let mut sent = 0usize;
|
||||
for idx in 0..wires.len() {
|
||||
if self.channel.send(&wires[idx]) {
|
||||
// Outbound wires can hold the logon token; clear each one once it is sent.
|
||||
wires[idx].zeroize();
|
||||
sent += 1;
|
||||
continue;
|
||||
}
|
||||
self.core.restore_outbound_wires_front(wires.split_off(idx));
|
||||
break;
|
||||
}
|
||||
sent
|
||||
}
|
||||
|
||||
pub fn handle_channel_message(self: &Arc<Self>, bytes: &[u8]) -> InboundAction {
|
||||
self.handle_message_at(bytes, 0)
|
||||
}
|
||||
|
||||
fn handle_message_at(self: &Arc<Self>, bytes: &[u8], depth: u32) -> InboundAction {
|
||||
let Some(envelope) = decode_proto_envelope(bytes) else {
|
||||
return self.handle_non_proto_message(bytes);
|
||||
};
|
||||
self.process_envelope(envelope.emsg, &envelope.header, &envelope.body, depth)
|
||||
}
|
||||
|
||||
fn process_envelope(
|
||||
self: &Arc<Self>,
|
||||
emsg: EMsg,
|
||||
header: &CMsgProtoBufHeader,
|
||||
body: &[u8],
|
||||
depth: u32,
|
||||
) -> InboundAction {
|
||||
let action = self.core.route_inbound(emsg, header, body);
|
||||
match &action {
|
||||
InboundAction::Multi => {
|
||||
if depth >= MAX_MULTI_DEPTH {
|
||||
return InboundAction::ParseFailed("MULTI nested too deep");
|
||||
}
|
||||
if let Some(records) = decode_multi_records(body) {
|
||||
for record in records {
|
||||
self.handle_message_at(&record, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
InboundAction::DeliverJob(result) => {
|
||||
self.jobs.deliver(
|
||||
header.jobid_target,
|
||||
result.eresult,
|
||||
result.error_message.clone(),
|
||||
&result.body,
|
||||
);
|
||||
}
|
||||
InboundAction::LogonOk => {
|
||||
// No persona or friends traffic: this session exists only to download.
|
||||
self.start_heartbeat_from_logon(body);
|
||||
self.notify_state(ClientState::LoggedOn);
|
||||
self.notify_client_message(emsg, header, body);
|
||||
}
|
||||
InboundAction::LoggedOff => {
|
||||
self.heartbeat.lock().expect("heartbeat poisoned").stop();
|
||||
self.notify_state(self.core.state());
|
||||
self.notify_client_message(emsg, header, body);
|
||||
}
|
||||
InboundAction::Ignored | InboundAction::ParseFailed(_) => {}
|
||||
InboundAction::PicsProductInfo => self.handle_pics_product_info(header, body),
|
||||
InboundAction::LicenseList(_) | InboundAction::ClientMessage => {
|
||||
self.notify_client_message(emsg, header, body);
|
||||
}
|
||||
}
|
||||
action
|
||||
}
|
||||
|
||||
fn on_channel_connected(self: &Arc<Self>) {
|
||||
// Always send ClientHello first; pre-existing queued wires (e.g. a
|
||||
// logon enqueued before the channel finished negotiating) must come
|
||||
// after the Hello or Steam rejects the conversation as malformed.
|
||||
// If a Hello was already prequeued, do not duplicate it.
|
||||
let queued = self.core.take_outbound_wires();
|
||||
let head_is_hello = queued
|
||||
.first()
|
||||
.and_then(|wire| decode_proto_envelope(wire))
|
||||
.is_some_and(|env| env.emsg == EMsg::CLIENT_HELLO);
|
||||
let combined = if head_is_hello {
|
||||
queued
|
||||
} else {
|
||||
let hello = self.core.build_client_hello().wire;
|
||||
let mut combined = Vec::with_capacity(queued.len() + 1);
|
||||
combined.push(hello);
|
||||
combined.extend(queued);
|
||||
combined
|
||||
};
|
||||
self.core.restore_outbound_wires_front(combined);
|
||||
// Connected is published only once Hello heads the queue, so a logon queued by a waiter
|
||||
// that wakes on it cannot get ahead of the Hello.
|
||||
self.core.set_state(ClientState::Connected);
|
||||
self.notify_state(ClientState::Connected);
|
||||
self.flush_outbound();
|
||||
}
|
||||
|
||||
fn on_channel_disconnected(self: &Arc<Self>, _reason: ChannelDisconnectReason, detail: &str) {
|
||||
self.heartbeat.lock().expect("heartbeat poisoned").stop();
|
||||
self.jobs
|
||||
.fail_all(&format!("channel disconnected: {detail}"));
|
||||
self.pics_product_info
|
||||
.lock()
|
||||
.expect("pics product info poisoned")
|
||||
.clear();
|
||||
self.core.reset_session_identity();
|
||||
self.core.set_state(ClientState::Disconnected);
|
||||
self.notify_state(ClientState::Disconnected);
|
||||
}
|
||||
|
||||
fn handle_pics_product_info(&self, header: &CMsgProtoBufHeader, body: &[u8]) {
|
||||
if header.jobid_target == INVALID_JOB_ID {
|
||||
return;
|
||||
}
|
||||
let mut pending = self
|
||||
.pics_product_info
|
||||
.lock()
|
||||
.expect("pics product info poisoned");
|
||||
// Fragments of jobs that timed out or failed are dropped, and a late one starts nothing.
|
||||
pending.retain(|job, _| self.jobs.is_tracked(*job));
|
||||
let Some(response) = CMsgClientPICSProductInfoResponse::deserialize(body) else {
|
||||
pending.remove(&header.jobid_target);
|
||||
drop(pending);
|
||||
// 0 (Invalid) is a failure to every caller; -1 would be delivered as success.
|
||||
self.jobs.deliver(
|
||||
header.jobid_target,
|
||||
0,
|
||||
"PICS product-info parse failed".to_string(),
|
||||
&[],
|
||||
);
|
||||
return;
|
||||
};
|
||||
if !self.jobs.is_tracked(header.jobid_target) {
|
||||
return;
|
||||
}
|
||||
if response.response_pending {
|
||||
let acc = pending.entry(header.jobid_target).or_default();
|
||||
merge_pics_product_info(acc, response);
|
||||
return;
|
||||
}
|
||||
let mut merged = pending.remove(&header.jobid_target).unwrap_or_default();
|
||||
merge_pics_product_info(&mut merged, response);
|
||||
let body = merged.serialize();
|
||||
self.jobs
|
||||
.deliver(header.jobid_target, 1, String::new(), &body);
|
||||
}
|
||||
|
||||
fn start_heartbeat_from_logon(self: &Arc<Self>, body: &[u8]) {
|
||||
let Some(resp) = CMsgClientLogonResponse::deserialize(body) else {
|
||||
return;
|
||||
};
|
||||
if resp.heartbeat_seconds <= 0 {
|
||||
return;
|
||||
}
|
||||
let weak = Arc::downgrade(self);
|
||||
let interval = Duration::from_secs(resp.heartbeat_seconds as u64);
|
||||
self.heartbeat
|
||||
.lock()
|
||||
.expect("heartbeat poisoned")
|
||||
.start(interval, move || {
|
||||
if let Some(runtime) = weak.upgrade() {
|
||||
runtime
|
||||
.core
|
||||
.enqueue_wire(runtime.core.build_heartbeat().wire);
|
||||
runtime.flush_outbound();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn handle_non_proto_message(&self, bytes: &[u8]) -> InboundAction {
|
||||
if bytes.len() >= 4 {
|
||||
let raw = read_u32_le(bytes);
|
||||
if !has_proto_flag(raw) {
|
||||
let legacy = strip_proto_flag(raw);
|
||||
if legacy == EMsg::CHANNEL_ENCRYPT_REQUEST
|
||||
|| legacy == EMsg::CHANNEL_ENCRYPT_RESPONSE
|
||||
|| legacy == EMsg::CHANNEL_ENCRYPT_RESULT
|
||||
{
|
||||
return InboundAction::Ignored;
|
||||
}
|
||||
}
|
||||
}
|
||||
InboundAction::ParseFailed("ProtoEnvelope")
|
||||
}
|
||||
|
||||
fn notify_state(&self, state: ClientState) {
|
||||
if let Some(callback) = self
|
||||
.on_state
|
||||
.lock()
|
||||
.expect("runtime callback poisoned")
|
||||
.as_ref()
|
||||
{
|
||||
let _ = panic::catch_unwind(AssertUnwindSafe(|| callback(state)));
|
||||
}
|
||||
}
|
||||
|
||||
fn notify_client_message(&self, emsg: EMsg, header: &CMsgProtoBufHeader, body: &[u8]) {
|
||||
if let Some(callback) = self
|
||||
.on_client_message
|
||||
.lock()
|
||||
.expect("runtime callback poisoned")
|
||||
.as_ref()
|
||||
{
|
||||
let _ = panic::catch_unwind(AssertUnwindSafe(|| callback(emsg, header, body)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_pics_product_info(
|
||||
acc: &mut CMsgClientPICSProductInfoResponse,
|
||||
mut next: CMsgClientPICSProductInfoResponse,
|
||||
) {
|
||||
acc.apps.append(&mut next.apps);
|
||||
acc.packages.append(&mut next.packages);
|
||||
acc.unknown_appids.append(&mut next.unknown_appids);
|
||||
acc.unknown_packageids.append(&mut next.unknown_packageids);
|
||||
if next.http_min_size > 0 {
|
||||
acc.http_min_size = next.http_min_size;
|
||||
}
|
||||
if !next.http_host.is_empty() {
|
||||
acc.http_host = next.http_host;
|
||||
}
|
||||
acc.meta_data_only = next.meta_data_only;
|
||||
acc.response_pending = false;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::steam::proto_envelope::encode_proto_envelope;
|
||||
use crate::steam::proto_wire::Writer as ProtoWriter;
|
||||
use crate::steam::transport::{ConnectedCallback, DisconnectedCallback, MessageCallback};
|
||||
use crate::steam::transport::{TransportDisconnectReason, TransportState};
|
||||
use crate::steam::wire_format::Writer as WireWriter;
|
||||
use std::sync::mpsc;
|
||||
|
||||
#[test]
|
||||
fn connected_channel_sends_client_hello_and_reports_state() {
|
||||
let shared = Arc::new(MockTransportState::default());
|
||||
let runtime = runtime_with_shared_transport(Arc::clone(&shared));
|
||||
let states = Arc::new(Mutex::new(Vec::new()));
|
||||
let states_cb = Arc::clone(&states);
|
||||
runtime.set_on_state(move |state| states_cb.lock().unwrap().push(state));
|
||||
|
||||
assert!(runtime.connect("wss://cm.example.com:443/cmsocket/"));
|
||||
shared.fire_connected();
|
||||
|
||||
assert_eq!(
|
||||
states.lock().unwrap().as_slice(),
|
||||
&[ClientState::Connecting, ClientState::Connected]
|
||||
);
|
||||
let sent = shared.take_sent();
|
||||
assert_eq!(
|
||||
decode_proto_envelope(&sent[0]).unwrap().emsg,
|
||||
EMsg::CLIENT_HELLO
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connected_channel_flushes_prequeued_hello_without_duplicate() {
|
||||
let shared = Arc::new(MockTransportState::default());
|
||||
let runtime = runtime_with_shared_transport(Arc::clone(&shared));
|
||||
runtime
|
||||
.core
|
||||
.enqueue_wire(runtime.core.build_client_hello().wire);
|
||||
|
||||
assert!(runtime.connect("wss://cm.example.com:443/cmsocket/"));
|
||||
shared.fire_connected();
|
||||
|
||||
let sent = shared.take_sent();
|
||||
assert_eq!(sent.len(), 1);
|
||||
assert_eq!(
|
||||
decode_proto_envelope(&sent[0]).unwrap().emsg,
|
||||
EMsg::CLIENT_HELLO
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flush_outbound_preserves_core_queue_order() {
|
||||
let shared = Arc::new(MockTransportState::default());
|
||||
let runtime = runtime_with_shared_transport(Arc::clone(&shared));
|
||||
assert!(runtime.connect("wss://cm.example.com:443/cmsocket/"));
|
||||
shared.fire_connected();
|
||||
shared.take_sent();
|
||||
|
||||
runtime.core.enqueue_wire(vec![1, 2, 3]);
|
||||
runtime.core.enqueue_wire(vec![4, 5, 6]);
|
||||
assert_eq!(runtime.flush_outbound(), 2);
|
||||
assert_eq!(shared.take_sent(), vec![vec![1, 2, 3], vec![4, 5, 6]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inbound_job_response_is_delivered() {
|
||||
let shared = Arc::new(MockTransportState::default());
|
||||
let runtime = runtime_with_shared_transport(shared);
|
||||
let job_id = runtime.next_job_id();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
runtime.track_job(job_id, move |result| tx.send(result).unwrap(), None);
|
||||
|
||||
let header = CMsgProtoBufHeader {
|
||||
jobid_target: job_id,
|
||||
eresult: 1,
|
||||
..Default::default()
|
||||
};
|
||||
let wire = encode_proto_envelope(EMsg::SERVICE_METHOD_RESPONSE, &header, b"reply");
|
||||
assert_eq!(
|
||||
runtime.handle_channel_message(&wire),
|
||||
InboundAction::DeliverJob(JobResult {
|
||||
eresult: 1,
|
||||
error_message: String::new(),
|
||||
body: b"reply".to_vec(),
|
||||
synthetic_failure: false,
|
||||
})
|
||||
);
|
||||
assert_eq!(rx.recv().unwrap().body, b"reply");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_records_are_redispatched() {
|
||||
let shared = Arc::new(MockTransportState::default());
|
||||
let runtime = runtime_with_shared_transport(shared);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
runtime.set_on_client_message(move |emsg, _, body| {
|
||||
tx.send((emsg, body.to_vec())).unwrap();
|
||||
});
|
||||
|
||||
let inner = encode_proto_envelope(
|
||||
EMsg::CLIENT_SESSION_TOKEN,
|
||||
&CMsgProtoBufHeader::default(),
|
||||
&account_info_body("Ada"),
|
||||
);
|
||||
let mut records = Vec::new();
|
||||
WireWriter::new(&mut records).u32(inner.len() as u32);
|
||||
records.extend_from_slice(&inner);
|
||||
let mut multi_body = Vec::new();
|
||||
ProtoWriter::new(&mut multi_body).bytes_field(2, &records);
|
||||
let multi = encode_proto_envelope(EMsg::MULTI, &CMsgProtoBufHeader::default(), &multi_body);
|
||||
|
||||
assert_eq!(runtime.handle_channel_message(&multi), InboundAction::Multi);
|
||||
assert_eq!(
|
||||
rx.recv().unwrap(),
|
||||
(EMsg::CLIENT_SESSION_TOKEN, account_info_body("Ada"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_channel_encrypt_frames_are_ignored() {
|
||||
let shared = Arc::new(MockTransportState::default());
|
||||
let runtime = runtime_with_shared_transport(shared);
|
||||
let mut legacy = Vec::new();
|
||||
WireWriter::new(&mut legacy).u32(EMsg::CHANNEL_ENCRYPT_REQUEST.0);
|
||||
assert_eq!(
|
||||
runtime.handle_channel_message(&legacy),
|
||||
InboundAction::Ignored
|
||||
);
|
||||
}
|
||||
|
||||
fn runtime_with_shared_transport(shared: Arc<MockTransportState>) -> Arc<CMClientRuntime> {
|
||||
CMClientRuntime::new(
|
||||
Arc::new(CMClientCore::default()),
|
||||
Box::new(MockTransport { shared }),
|
||||
)
|
||||
}
|
||||
|
||||
fn account_info_body(name: &str) -> Vec<u8> {
|
||||
let mut body = Vec::new();
|
||||
ProtoWriter::new(&mut body).string_field(1, name);
|
||||
body
|
||||
}
|
||||
|
||||
struct MockTransportState {
|
||||
state: Mutex<TransportState>,
|
||||
connected: Mutex<Option<ConnectedCallback>>,
|
||||
disconnected: Mutex<Option<DisconnectedCallback>>,
|
||||
message: Mutex<Option<MessageCallback>>,
|
||||
sent: Mutex<Vec<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl Default for MockTransportState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
state: Mutex::new(TransportState::Disconnected),
|
||||
connected: Mutex::new(None),
|
||||
disconnected: Mutex::new(None),
|
||||
message: Mutex::new(None),
|
||||
sent: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MockTransportState {
|
||||
fn fire_connected(&self) {
|
||||
*self.state.lock().unwrap() = TransportState::Connected;
|
||||
if let Some(callback) = self.connected.lock().unwrap().as_ref() {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn fire_disconnected(&self, reason: TransportDisconnectReason, detail: &str) {
|
||||
*self.state.lock().unwrap() = TransportState::Disconnected;
|
||||
if let Some(callback) = self.disconnected.lock().unwrap().as_ref() {
|
||||
callback(reason, detail);
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn fire_message(&self, bytes: &[u8]) {
|
||||
if let Some(callback) = self.message.lock().unwrap().as_ref() {
|
||||
callback(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
fn take_sent(&self) -> Vec<Vec<u8>> {
|
||||
std::mem::take(&mut *self.sent.lock().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
struct MockTransport {
|
||||
shared: Arc<MockTransportState>,
|
||||
}
|
||||
|
||||
impl Transport for MockTransport {
|
||||
fn connect(&mut self, _url: &str) -> bool {
|
||||
*self.shared.state.lock().unwrap() = TransportState::Connecting;
|
||||
true
|
||||
}
|
||||
|
||||
fn send(&mut self, data: &[u8]) -> bool {
|
||||
if self.state() != TransportState::Connected {
|
||||
return false;
|
||||
}
|
||||
self.shared.sent.lock().unwrap().push(data.to_vec());
|
||||
true
|
||||
}
|
||||
|
||||
fn disconnect(&mut self) {
|
||||
*self.shared.state.lock().unwrap() = TransportState::Disconnected;
|
||||
}
|
||||
|
||||
fn state(&self) -> TransportState {
|
||||
*self.shared.state.lock().unwrap()
|
||||
}
|
||||
|
||||
fn set_on_message(&mut self, cb: MessageCallback) {
|
||||
*self.shared.message.lock().unwrap() = Some(cb);
|
||||
}
|
||||
|
||||
fn set_on_connected(&mut self, cb: ConnectedCallback) {
|
||||
*self.shared.connected.lock().unwrap() = Some(cb);
|
||||
}
|
||||
|
||||
fn set_on_disconnected(&mut self, cb: DisconnectedCallback) {
|
||||
*self.shared.disconnected.lock().unwrap() = Some(cb);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
#[repr(u8)]
|
||||
pub enum CmTransport {
|
||||
#[default]
|
||||
Unknown = 0,
|
||||
WebSocket = 1,
|
||||
Tcp = 2,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct CmServer {
|
||||
pub endpoint: String,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub transport: CmTransport,
|
||||
pub realm: String,
|
||||
pub datacenter: String,
|
||||
pub load: i32,
|
||||
pub weighted_load: f32,
|
||||
}
|
||||
|
||||
impl CmServer {
|
||||
pub fn websocket_url(&self) -> String {
|
||||
if self.transport != CmTransport::WebSocket || self.host.is_empty() || self.port == 0 {
|
||||
return String::new();
|
||||
}
|
||||
if self.host.contains(':') && !self.host.starts_with('[') {
|
||||
format!("wss://[{}]:{}/cmsocket/", self.host, self.port)
|
||||
} else {
|
||||
format!("wss://{}:{}/cmsocket/", self.host, self.port)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_endpoint(endpoint: &str) -> Option<(String, u16)> {
|
||||
let colon = endpoint.rfind(':')?;
|
||||
if colon == 0 || colon + 1 == endpoint.len() {
|
||||
return None;
|
||||
}
|
||||
let mut host = &endpoint[..colon];
|
||||
if host.len() >= 2 && host.starts_with('[') && host.ends_with(']') {
|
||||
host = &host[1..host.len() - 1];
|
||||
}
|
||||
let port_text = &endpoint[colon + 1..];
|
||||
if !port_text.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let port = port_text.parse::<u32>().ok()?;
|
||||
if port == 0 || port > u16::MAX as u32 {
|
||||
return None;
|
||||
}
|
||||
Some((host.to_string(), port as u16))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_host_port_and_ipv6_brackets() {
|
||||
assert_eq!(
|
||||
parse_endpoint("cm.example.com:443"),
|
||||
Some(("cm.example.com".to_string(), 443))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_endpoint("[2001:db8::1]:27017"),
|
||||
Some(("2001:db8::1".to_string(), 27017))
|
||||
);
|
||||
assert_eq!(parse_endpoint("missing-port"), None);
|
||||
assert_eq!(parse_endpoint("host:0"), None);
|
||||
assert_eq!(parse_endpoint("host:+443"), None);
|
||||
assert_eq!(parse_endpoint("host:70000"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn websocket_url_requires_websocket_transport() {
|
||||
let server = CmServer {
|
||||
host: "cm.example.com".to_string(),
|
||||
port: 443,
|
||||
transport: CmTransport::WebSocket,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(server.websocket_url(), "wss://cm.example.com:443/cmsocket/");
|
||||
let (host, port) = parse_endpoint("[2001:db8::1]:27017").unwrap();
|
||||
let v6 = CmServer {
|
||||
host,
|
||||
port,
|
||||
transport: CmTransport::WebSocket,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(v6.websocket_url(), "wss://[2001:db8::1]:27017/cmsocket/");
|
||||
}
|
||||
}
|
||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user