Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef1221cf05 | ||
|
|
090b87c37c | ||
|
|
ab7390e844 | ||
|
|
ea8feebea7 | ||
|
|
3ccf8ca01a | ||
|
|
be51429fa4 | ||
|
|
3df06f48b7 | ||
|
|
48ad5506b6 | ||
|
|
2229dbc0a8 | ||
|
|
8858285d13 | ||
|
|
67034e5f3d | ||
|
|
cd09deddba | ||
|
|
aef1f85aa9 | ||
|
|
198f667bf0 | ||
|
|
52fa41767c | ||
|
|
6469a7693c | ||
|
|
cd1caf523d | ||
|
|
37e0f30cc6 | ||
|
|
23811147aa |
No files matched your search
@@ -49,6 +49,10 @@ jobs:
|
||||
with:
|
||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/docs/releases/media/
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
- name: Pin and merge the APK source
|
||||
id: merge
|
||||
@@ -82,6 +86,10 @@ jobs:
|
||||
with:
|
||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/docs/releases/media/
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
- name: Merge the pinned APK base
|
||||
if: github.event_name == 'pull_request'
|
||||
@@ -136,6 +144,10 @@ jobs:
|
||||
with:
|
||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/docs/releases/media/
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
- name: Merge the pinned APK base
|
||||
if: github.event_name == 'pull_request'
|
||||
@@ -287,6 +299,10 @@ jobs:
|
||||
with:
|
||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/docs/releases/media/
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Check human authorship
|
||||
@@ -530,13 +546,6 @@ jobs:
|
||||
git diff --exit-code -- app/src/main/rust/stores/Cargo.lock \
|
||||
|| { echo "::error::Cargo.lock changed during the build; commit the regenerated lockfile (uploaded as stores-cargo-lock)"; exit 1; }
|
||||
|
||||
- name: Store engines host unit tests
|
||||
timeout-minutes: 10
|
||||
continue-on-error: true
|
||||
run: |
|
||||
cd app/src/main/rust/stores
|
||||
cargo test --locked 2>&1 | tail -60
|
||||
|
||||
- name: Upload the regenerated Cargo.lock
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -626,6 +635,63 @@ jobs:
|
||||
APK_OUTCOME: ${{ steps.apk-upload.outcome }}
|
||||
run: bash tools/release/report-build.sh
|
||||
|
||||
store-tests:
|
||||
name: Store engines host tests
|
||||
needs: source
|
||||
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
continue-on-error: true
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/docs/releases/media/
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
- name: Merge the pinned APK base
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch --no-tags origin "$BUILD_BASE_SHA"
|
||||
git config user.name "ci"
|
||||
git config user.email "ci@users.noreply.github.com"
|
||||
git merge --no-ff --no-edit FETCH_HEAD
|
||||
- name: Verify backend and test source match
|
||||
env:
|
||||
XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
||||
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
|
||||
- name: Rust toolchain
|
||||
id: rust
|
||||
run: echo "rustc=$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT"
|
||||
- name: Cache cargo registry and the host test target
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
app/src/main/rust/stores/target
|
||||
key: stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-${{ hashFiles('app/src/main/rust/stores/src/**', 'app/src/main/rust/stores/Cargo.toml', 'app/src/main/rust/stores/build.rs') }}
|
||||
restore-keys: |
|
||||
stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-
|
||||
stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-
|
||||
- name: Store engines host unit tests
|
||||
timeout-minutes: 10
|
||||
continue-on-error: true
|
||||
run: |
|
||||
set -o pipefail
|
||||
cd app/src/main/rust/stores
|
||||
cargo test --locked 2>&1 | tail -60
|
||||
|
||||
python-tests:
|
||||
name: Python and native regression tests
|
||||
needs: source
|
||||
@@ -637,6 +703,10 @@ jobs:
|
||||
with:
|
||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/docs/releases/media/
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
- name: Merge the pinned APK base
|
||||
if: github.event_name == 'pull_request'
|
||||
|
||||
@@ -286,6 +286,13 @@ if (uvcDir) {
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) }
|
||||
|
||||
def stageGogNotices = tasks.register('stageGogNotices', Copy) {
|
||||
from(layout.projectDirectory.dir('src/main/rust/stores/vendor/xdelta3')) { include 'LICENSE', 'README.droiddeck.md' }
|
||||
into(layout.buildDirectory.dir('gogNotices/licenses/xdelta3'))
|
||||
}
|
||||
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('gogNotices'))
|
||||
tasks.named('preBuild').configure { dependsOn(stageGogNotices) }
|
||||
|
||||
def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
|
||||
mustRunAfter(stageSessionScripts, stageRuntimeAssets)
|
||||
workingDir rootProject.projectDir
|
||||
@@ -303,6 +310,8 @@ def buildRustStores = tasks.register('buildRustStores', Exec) {
|
||||
description = 'Cross-compiles the store download engines (libdroiddeckstores.so) with cargo-ndk.'
|
||||
onlyIf { !skipRust }
|
||||
inputs.dir(rustCrateDir.dir('src'))
|
||||
inputs.dir(rustCrateDir.dir('vendor'))
|
||||
inputs.file(rustCrateDir.file('build.rs'))
|
||||
inputs.files(rustCrateDir.file('Cargo.toml'), rustCrateDir.file('Cargo.lock'))
|
||||
inputs.property('ndkVersion', android.ndkVersion)
|
||||
if (!skipRust) inputs.property('rustToolchain', providers.exec {
|
||||
|
||||
@@ -1036,9 +1036,35 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onPlay = { playSteam() },
|
||||
onPlaySteamVr = { playSteamVr() },
|
||||
onSteamUrl = { url ->
|
||||
if (!SessionState.running) startSession(
|
||||
Intent(this, SessionActivity::class.java).putExtra(SessionService.EXTRA_STEAM_URL, url), steamSession = true,
|
||||
)
|
||||
if (!com.droiddeck.launcher.session.SteamSessionUrl.isSupported(url)) {
|
||||
android.widget.Toast.makeText(this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG).show()
|
||||
} else if (!SessionState.running) {
|
||||
android.widget.Toast.makeText(this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG).show()
|
||||
} else if (SessionState.mode != SessionService.MODE_STEAM) {
|
||||
android.widget.Toast.makeText(this, R.string.steam_navigation_switch_mode, android.widget.Toast.LENGTH_LONG).show()
|
||||
} else if (SessionState.stopRequested) {
|
||||
android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
|
||||
} else {
|
||||
if (SessionState.suspended) SessionService.resume(this)
|
||||
val context = applicationContext
|
||||
val sessionId = SessionState.sessionId
|
||||
Thread({
|
||||
val opened = runCatching {
|
||||
com.droiddeck.launcher.agent.AgentGuest.openSteamUrl(context, url)
|
||||
}.isSuccess
|
||||
ui.post {
|
||||
val canResume = com.droiddeck.launcher.session.SteamSessionUrl.canResume(
|
||||
sessionId, SessionState.sessionId, SessionState.running,
|
||||
SessionState.stopRequested, isDestroyed,
|
||||
)
|
||||
if (opened && canResume) startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
||||
else if (!opened && !isDestroyed) android.widget.Toast.makeText(
|
||||
this, R.string.steam_navigation_failed, android.widget.Toast.LENGTH_LONG,
|
||||
).show()
|
||||
}
|
||||
}, "steam-navigation").start()
|
||||
}
|
||||
},
|
||||
onPlayDesktopUi = {
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
@@ -1049,7 +1075,11 @@ class FrontEndActivity : ComponentActivity() {
|
||||
if (shortcutPicker) chooseGameShortcut(g)
|
||||
else {
|
||||
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g)
|
||||
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) }
|
||||
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g, onBlocked = {
|
||||
android.widget.Toast.makeText(
|
||||
this, R.string.store_maintenance_launch_blocked, android.widget.Toast.LENGTH_LONG,
|
||||
).show()
|
||||
}) { launchGame(g) }
|
||||
}
|
||||
},
|
||||
onEpicLauncher = { openEpicLauncher() },
|
||||
@@ -1315,7 +1345,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
showPhantomGate = true
|
||||
},
|
||||
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
|
||||
onStartPairingGuide = { displayId -> PairingGuideActivity.start(this, displayId) },
|
||||
onStartPairingGuide = { displayId, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) },
|
||||
onOpenNotificationSettings = {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
|
||||
|
||||
@@ -58,6 +58,7 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.core.AppLanguage
|
||||
import com.droiddeck.launcher.core.GlobalSettings
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
@@ -67,9 +68,10 @@ import com.droiddeck.launcher.ui.SecondaryButton
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
class PairingGuideActivity : ComponentActivity() {
|
||||
enum class Step { BUILD_NUMBER, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
|
||||
enum class Step { BUILD_NUMBER, CHILD_PROCESS, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
|
||||
|
||||
private var settingsDisplay: Int? = null
|
||||
private var toggleOnly = false
|
||||
private var inPip by mutableStateOf(false)
|
||||
private var launchPending = false
|
||||
|
||||
@@ -78,6 +80,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
||||
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
|
||||
setContent { DroidDeckTheme { Guide() } }
|
||||
launchPending = savedInstanceState == null
|
||||
}
|
||||
@@ -86,6 +89,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
||||
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
|
||||
launchPending = true
|
||||
}
|
||||
|
||||
@@ -108,7 +112,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
|
||||
private fun launchSettings() {
|
||||
launchPending = false
|
||||
openSettings(stepFor(this, WirelessAdbPairingService.stage.value))
|
||||
openSettings(stepFor(SettingsState.read(this), WirelessAdbPairingService.stage.value, toggleOnly))
|
||||
}
|
||||
|
||||
private fun enterPip() {
|
||||
@@ -121,7 +125,9 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
val intent = if (step == Step.BUILD_NUMBER) {
|
||||
Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number")
|
||||
} else {
|
||||
Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
|
||||
Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).apply {
|
||||
if (step != Step.CHILD_PROCESS) putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
|
||||
}
|
||||
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val display = settingsDisplay
|
||||
runCatching {
|
||||
@@ -147,10 +153,10 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
delay(500)
|
||||
}
|
||||
}
|
||||
val step = stepFor(settingsState, stage)
|
||||
val step = stepFor(settingsState, stage, toggleOnly)
|
||||
var previous by remember { mutableStateOf(step) }
|
||||
LaunchedEffect(step) {
|
||||
if (previous == Step.BUILD_NUMBER && step == Step.WIRELESS_DEBUGGING) openSettings(step)
|
||||
if (previous == Step.BUILD_NUMBER && (step == Step.WIRELESS_DEBUGGING || step == Step.CHILD_PROCESS)) openSettings(step)
|
||||
previous = step
|
||||
when (step) {
|
||||
Step.DONE -> { delay(1_500); returnToApp() }
|
||||
@@ -158,7 +164,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
LaunchedEffect(stage) { if (stage == Stage.Idle) finish() }
|
||||
LaunchedEffect(stage) { if (stage == Stage.Idle && !toggleOnly) finish() }
|
||||
BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() }
|
||||
|
||||
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {
|
||||
@@ -199,7 +205,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
openSettings(step)
|
||||
})
|
||||
SecondaryButton(stringResource(R.string.common_cancel), onClick = {
|
||||
WirelessAdbPairingService.cancel(this@PairingGuideActivity)
|
||||
if (!toggleOnly) WirelessAdbPairingService.cancel(this@PairingGuideActivity)
|
||||
returnToApp()
|
||||
})
|
||||
}
|
||||
@@ -210,6 +216,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
@Composable
|
||||
private fun instruction(step: Step, stage: Stage): String = when (step) {
|
||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_build_number)
|
||||
Step.CHILD_PROCESS -> stringResource(R.string.pairguide_child_process)
|
||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_wireless)
|
||||
Step.PAIR -> stringResource(R.string.pairguide_pair)
|
||||
Step.CODE -> (stage as? Stage.CodeNeeded)?.error ?: stringResource(R.string.gate_step3)
|
||||
@@ -226,6 +233,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
val beat by pulse.animateFloat(0f, 1f, infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Restart), label = "beat")
|
||||
val label = when (step) {
|
||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_row_build_number)
|
||||
Step.CHILD_PROCESS -> stringResource(R.string.pairguide_row_child_process)
|
||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_row_wireless)
|
||||
Step.PAIR -> stringResource(R.string.pairguide_row_pair)
|
||||
Step.CODE -> stringResource(R.string.adbpair_enter_code)
|
||||
@@ -240,7 +248,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
Text(label, style = if (compact) MaterialTheme.typography.labelMedium else MaterialTheme.typography.bodyLarge,
|
||||
color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
when (step) {
|
||||
Step.WIRELESS_DEBUGGING -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
|
||||
Step.WIRELESS_DEBUGGING, Step.CHILD_PROCESS -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
|
||||
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (step == Step.BUILD_NUMBER) Text("×7", style = MaterialTheme.typography.labelLarge, color = accent)
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
@@ -267,7 +275,8 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
@Composable
|
||||
private fun StepDots(step: Step) {
|
||||
val accent = LocalPalette.current.signal
|
||||
val shown = listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
|
||||
val shown = if (toggleOnly) listOf(Step.BUILD_NUMBER, Step.CHILD_PROCESS)
|
||||
else listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
|
||||
val at = shown.indexOf(step).takeIf { it >= 0 } ?: shown.size
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
shown.forEachIndexed { index, _ ->
|
||||
@@ -278,22 +287,30 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private data class SettingsState(val developerOptions: Boolean, val wirelessDebugging: Boolean) {
|
||||
private data class SettingsState(
|
||||
val developerOptions: Boolean,
|
||||
val wirelessDebugging: Boolean,
|
||||
val childProcessBlocked: Boolean,
|
||||
) {
|
||||
companion object {
|
||||
fun read(context: Context) = SettingsState(
|
||||
GlobalSettings.developerOptionsOn(context),
|
||||
GlobalSettings.wirelessDebuggingOn(context),
|
||||
PhantomProcessLimit.blocksSteam(PhantomProcessLimit.read(context)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val EXTRA_DISPLAY = "settingsDisplay"
|
||||
private const val EXTRA_TOGGLE_ONLY = "toggleOnly"
|
||||
private const val HIGHLIGHT_KEY = ":settings:fragment_args_key"
|
||||
|
||||
private fun stepFor(context: Context, stage: Stage) = stepFor(SettingsState.read(context), stage)
|
||||
|
||||
private fun stepFor(settings: SettingsState, stage: Stage): Step = when (stage) {
|
||||
private fun stepFor(settings: SettingsState, stage: Stage, toggleOnly: Boolean): Step = if (toggleOnly) when {
|
||||
!settings.developerOptions -> Step.BUILD_NUMBER
|
||||
settings.childProcessBlocked -> Step.CHILD_PROCESS
|
||||
else -> Step.DONE
|
||||
} else when (stage) {
|
||||
is Stage.Working -> Step.WORKING
|
||||
Stage.Done -> Step.DONE
|
||||
is Stage.Failed -> Step.FAILED
|
||||
@@ -317,10 +334,11 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
return mode == AppOpsManager.MODE_ALLOWED
|
||||
}
|
||||
|
||||
fun start(context: Context, settingsDisplay: Int?): Boolean {
|
||||
fun start(context: Context, settingsDisplay: Int?, toggleOnly: Boolean = false): Boolean {
|
||||
if (settingsDisplay == null && !canFloat(context)) return false
|
||||
context.startActivity(Intent(context, PairingGuideActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
.putExtra(EXTRA_TOGGLE_ONLY, toggleOnly)
|
||||
.apply { if (settingsDisplay != null) putExtra(EXTRA_DISPLAY, settingsDisplay) })
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ import android.os.FileObserver
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SteamSessionUrl
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
@@ -96,6 +98,16 @@ object AgentGuest {
|
||||
fun focus(context: Context): JSONObject? =
|
||||
if (SessionState.running) readJson(File(dir(context), "focus.json")) else null
|
||||
|
||||
fun openSteamUrl(context: Context, url: String, timeoutMs: Long = STEAM_URL_TIMEOUT_MS): JSONObject {
|
||||
require(SteamSessionUrl.isSupported(url)) { "Unsupported Steam navigation URL" }
|
||||
val result = call(context, JSONObject().put("kind", "steam-url").put("url", url)
|
||||
.put("timeout", (timeoutMs - 1_000).coerceAtLeast(1_000) / 1_000.0), timeoutMs, trusted = true)
|
||||
check(SteamSessionUrl.wasOpened(result.optBoolean("ok"), result.optBoolean("launched"))) {
|
||||
"Steam did not accept the navigation request"
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun selectedSteamAppId(context: Context): Long? {
|
||||
val result = call(context, JSONObject().put("kind", "steam-selection"), 6_000)
|
||||
if (!result.optBoolean("ok") || result.isNull("appId")) return null
|
||||
@@ -194,4 +206,6 @@ object AgentGuest {
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
private const val STEAM_URL_TIMEOUT_MS = 125_000L
|
||||
}
|
||||
@@ -74,6 +74,7 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
|
||||
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
|
||||
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
|
||||
"usr/local/bin/droiddeck-gog-maintenance" to "usr/local/bin/droiddeck-gog-maintenance",
|
||||
"usr/local/bin/droiddeck-battlenet" to "usr/local/bin/droiddeck-battlenet",
|
||||
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
|
||||
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
|
||||
|
||||
@@ -1195,7 +1195,7 @@ object SessionPrefs {
|
||||
resolutionChosen(context, SessionService.MODE_DESKTOP)) SessionService.MODE_DESKTOP
|
||||
else prefMode(mode)
|
||||
|
||||
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", false)
|
||||
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true)
|
||||
|
||||
fun setPipAutoEnter(context: Context, enabled: Boolean) {
|
||||
prefs(context).edit().putBoolean("pipAutoEnter", enabled).apply()
|
||||
@@ -1238,7 +1238,8 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
fun suspendPolicy(context: Context, mode: String): String =
|
||||
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
|
||||
prefs(context).getString("suspendPolicy.${prefMode(mode)}",
|
||||
if (mode == SessionService.MODE_STEAM) SUSPEND_NATIVE else SUSPEND_MANUAL)
|
||||
?.let { if (it == LEGACY_SUSPEND_DOWNLOADS) SUSPEND_AUTO else it }
|
||||
?.takeIf { it in setOf(SUSPEND_AUTO, SUSPEND_NATIVE, SUSPEND_MANUAL, SUSPEND_NEVER) }
|
||||
?.let { if (mode != SessionService.MODE_STEAM && it == SUSPEND_NATIVE) SUSPEND_AUTO else it }
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
object SteamSessionUrl {
|
||||
private val allowed = Regex("steam://(?:open/downloads|uninstall/[1-9][0-9]{0,9})")
|
||||
private const val MAX_STEAM_APP_ID = 4_294_967_295L
|
||||
|
||||
fun isSupported(url: String): Boolean {
|
||||
if (!allowed.matches(url)) return false
|
||||
val appId = url.removePrefix("steam://uninstall/").takeIf { it != url }?.toLongOrNull()
|
||||
return appId == null || appId <= MAX_STEAM_APP_ID
|
||||
}
|
||||
|
||||
internal fun wasOpened(ok: Boolean, launched: Boolean): Boolean = ok && launched
|
||||
|
||||
internal fun canResume(
|
||||
expectedSessionId: String?,
|
||||
currentSessionId: String?,
|
||||
running: Boolean,
|
||||
stopping: Boolean,
|
||||
activityDestroyed: Boolean,
|
||||
): Boolean = expectedSessionId != null && expectedSessionId == currentSessionId &&
|
||||
running && !stopping && !activityDestroyed
|
||||
}
|
||||
@@ -19,7 +19,7 @@ enum class Bucket { GAMES, GAME_DATA, TOOLS, COMPONENTS, STORES, DESKTOP, SYSTEM
|
||||
class GameUsage(
|
||||
val appId: Int, val name: String, val art: File?, val library: String, val internal: Boolean, val lastPlayed: Long,
|
||||
val game: Long, val prefix: Long, val shaders: Long, val workshop: Long, val shaderDir: File?,
|
||||
val x64: Boolean = false,
|
||||
val x64: Boolean = false, val prefixDir: File? = null,
|
||||
) {
|
||||
val data: Long get() = prefix + shaders + workshop
|
||||
val total: Long get() = game + data
|
||||
@@ -175,14 +175,16 @@ object StorageScan {
|
||||
}
|
||||
if (!m.installed) continue
|
||||
val gameBytes = dir?.let { File(lib.root, "steamapps/common/$it") }?.takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
|
||||
val prefix = File(lib.data, "steamapps/compatdata/${m.appId}").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
|
||||
val compatRoot = File(lib.data, "steamapps/compatdata").takeIf { it.isDirectory } ?: File(lib.root, "steamapps/compatdata")
|
||||
val prefixDir = File(compatRoot, m.appId.toString()).takeIf { it.isDirectory }
|
||||
val prefix = prefixDir?.let { walker.measure(it) } ?: 0
|
||||
val shaderDir = File(lib.data, "steamapps/shadercache/${m.appId}").takeIf { it.isDirectory }
|
||||
val shaders = shaderDir?.let { walker.measure(it) } ?: 0
|
||||
val workshop = File(lib.root, "steamapps/workshop/content/${m.appId}").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
|
||||
val known = art[lib.x64]?.get(m.appId)
|
||||
games.add(GameUsage(
|
||||
m.appId, known?.name ?: m.name, known?.art, lib.label, lib.internal, m.lastPlayed,
|
||||
gameBytes, prefix, shaders, workshop, shaderDir, lib.x64,
|
||||
gameBytes, prefix, shaders, workshop, shaderDir, lib.x64, prefixDir,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,6 +140,13 @@ object StorageState {
|
||||
FileOps.delete(dir)
|
||||
})
|
||||
|
||||
fun resetPrefix(context: Context, game: GameUsage) = act(context, "prefix-${game.appId}", { _, fresh ->
|
||||
val dir = fresh.games.firstOrNull { it.appId == game.appId && it.x64 == game.x64 && it.prefixDir?.path == game.prefixDir?.path }
|
||||
?.prefixDir ?: error("prefix not found")
|
||||
check(FileOps.delete(dir)) { "cannot delete $dir" }
|
||||
true
|
||||
})
|
||||
|
||||
fun removeLeftover(context: Context, l: Leftover) = act(context, "leftover-${l.appId}", { _, fresh ->
|
||||
val leftover = fresh.leftovers.firstOrNull { it.appId == l.appId && it.prefix?.path == l.prefix?.path && it.shaders?.path == l.shaders?.path }
|
||||
?: return@act false
|
||||
|
||||
@@ -254,6 +254,7 @@ object StoreInstallRoot {
|
||||
val sidecar = StoreGameSidecar.read(folder)
|
||||
when {
|
||||
sidecar == null -> Unfinished(store, null, folder)
|
||||
store == Store.GOG && sidecar.state == StoreGameSidecar.STATE_UPDATING -> null
|
||||
!sidecar.isInstalled -> Unfinished(store, sidecar.id, folder)
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -64,10 +64,21 @@ object StoreLaunch {
|
||||
private const val CODE_VAR = "DD_X"
|
||||
private const val CLIENT_VAR = "DD_A"
|
||||
|
||||
internal fun matchingInstalls(context: Context, store: Store, id: String): List<Pair<File, StoreGameSidecar>> =
|
||||
StoreInstallRoot.gameFolders(context.applicationContext).mapNotNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.takeIf { it.store == store && it.id == id }?.let { folder to it }
|
||||
}
|
||||
|
||||
internal fun findInstalled(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? =
|
||||
matchingInstalls(context, store, id).firstOrNull { it.second.isInstalled }
|
||||
|
||||
private fun preferredInstall(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? {
|
||||
val matches = matchingInstalls(context, store, id)
|
||||
return matches.firstOrNull { it.second.isInstalled } ?: matches.firstOrNull()
|
||||
}
|
||||
|
||||
fun installedGame(context: Context, store: Store, id: String): Library.SteamGame? {
|
||||
val folder = StoreInstallRoot.gameFolders(context).firstOrNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.let { it.store == store && it.id == id && it.isInstalled } == true
|
||||
} ?: return null
|
||||
val folder = findInstalled(context, store, id)?.first ?: return null
|
||||
val game = AddedGames.single(context, folder.path) ?: return null
|
||||
return Library.addedGame(context, game)
|
||||
}
|
||||
@@ -82,11 +93,22 @@ object StoreLaunch {
|
||||
}
|
||||
}
|
||||
|
||||
fun prepare(context: Context, store: Store, id: String, onReady: () -> Unit) {
|
||||
if (store != Store.EPIC) { onReady(); return }
|
||||
fun prepare(context: Context, store: Store, id: String, onBlocked: () -> Unit = {}, onReady: () -> Unit) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
epicCode(app, id)
|
||||
val selected = try {
|
||||
preferredInstall(app, store, id)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not inspect installed ${store.label} launch records for $id", e)
|
||||
return@Thread
|
||||
}
|
||||
if (selected != null && com.droiddeck.launcher.stores.maintenance.StoreMaintenance.launchExcluded(
|
||||
InstalledStoreGame(selected.second, selected.first))) {
|
||||
Log.i(TAG, "launch blocked while ${store.label} maintenance is active: $id")
|
||||
StoresState.post(onBlocked)
|
||||
return@Thread
|
||||
}
|
||||
if (store == Store.EPIC) epicCode(app, id)
|
||||
StoresState.post(onReady)
|
||||
}, "stores-launch-prep").start()
|
||||
}
|
||||
@@ -96,9 +118,10 @@ object StoreLaunch {
|
||||
fun epicCode(context: Context, id: String): CodeResult {
|
||||
val app = context.applicationContext
|
||||
val result = try {
|
||||
val folder = StoreInstallRoot.gameFolders(app).firstOrNull { f -> StoreGameSidecar.read(f)?.let { it.store == Store.EPIC && it.id == id } == true }
|
||||
val sidecar = folder?.let { StoreGameSidecar.read(it) }
|
||||
sidecar?.let { refreshLauncher(folder, it) }
|
||||
val selected = preferredInstall(app, Store.EPIC, id)
|
||||
val folder = selected?.first
|
||||
val sidecar = selected?.second
|
||||
selected?.let { (installedFolder, installedSidecar) -> refreshLauncher(installedFolder, installedSidecar) }
|
||||
val options = sidecar?.epic
|
||||
if (folder == null) CodeResult(false, "not-installed")
|
||||
else if (options != null && !options.wantsCode) {
|
||||
@@ -124,11 +147,11 @@ object StoreLaunch {
|
||||
return result
|
||||
}
|
||||
|
||||
fun prepare(context: Context, game: Library.SteamGame, onReady: () -> Unit) {
|
||||
fun prepare(context: Context, game: Library.SteamGame, onBlocked: () -> Unit = {}, onReady: () -> Unit) {
|
||||
val store = Store.byId(game.source)
|
||||
val id = game.storeId
|
||||
if (store == null || id == null) { onReady(); return }
|
||||
prepare(context, store, id, onReady)
|
||||
if (store == null || id == null) { StoresState.post(onReady); return }
|
||||
prepare(context, store, id, onBlocked = onBlocked, onReady = onReady)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
|
||||
object StoresState {
|
||||
private const val TAG = "Stores"
|
||||
@@ -72,7 +73,10 @@ object StoresState {
|
||||
|
||||
fun backend(store: Store): StoreBackend? = backends[store]
|
||||
|
||||
fun register(backend: StoreBackend) { backends[backend.store] = backend }
|
||||
fun register(backend: StoreBackend) {
|
||||
backends[backend.store] = backend
|
||||
backend.maintenanceAdapter()?.let(StoreMaintenance::register)
|
||||
}
|
||||
|
||||
fun refresh(context: Context) {
|
||||
val app = context.applicationContext
|
||||
@@ -81,7 +85,7 @@ object StoresState {
|
||||
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.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 }?.let { InstalledStoreGame(it, folder) }
|
||||
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
|
||||
} + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(app) }.getOrDefault(emptyList())
|
||||
val partial = StoreInstallRoot.unfinished(app)
|
||||
val version = if (StoresNative.available) StoresNative.version ?: "" else ""
|
||||
@@ -95,6 +99,8 @@ object StoresState {
|
||||
engine = version
|
||||
accountsLoaded = true
|
||||
}
|
||||
StoreMaintenance.checkInstalled(app, onDisk)
|
||||
com.droiddeck.launcher.stores.gog.GogMaintenance.checkInstalled(app, onDisk)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -179,6 +185,7 @@ object StoresState {
|
||||
}
|
||||
|
||||
fun signIn(context: Context, store: Store) {
|
||||
StoreMaintenance.invalidate(store)
|
||||
expired.remove(store)
|
||||
libraryAsked.remove(store)
|
||||
backends[store]?.signIn(context) ?: logLine("${store.label}: this build has no sign-in for it yet")
|
||||
@@ -189,6 +196,7 @@ object StoresState {
|
||||
background("stores-signout") {
|
||||
val backend = backends[store]
|
||||
backend?.signOut(app)
|
||||
StoreMaintenance.invalidate(store)
|
||||
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) }
|
||||
else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store)
|
||||
if (store == Store.ITCH) {
|
||||
@@ -274,7 +282,11 @@ object StoresState {
|
||||
fun uninstall(context: Context, game: InstalledStoreGame, onDone: () -> Unit = {}) {
|
||||
val app = context.applicationContext
|
||||
val key = "${game.sidecar.store.id}:${game.sidecar.id}"
|
||||
uninstalling[key] = 0f
|
||||
if (!com.droiddeck.launcher.stores.maintenance.StoreMaintenance.beginUninstall(game)) {
|
||||
android.widget.Toast.makeText(app, "Close, finish, or recover maintenance before uninstalling.", android.widget.Toast.LENGTH_LONG).show()
|
||||
onDone()
|
||||
return
|
||||
}
|
||||
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
|
||||
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
|
||||
if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) {
|
||||
@@ -347,4 +359,5 @@ interface StoreBackend {
|
||||
fun search(context: Context, query: String): List<CatalogItem> = emptyList()
|
||||
fun install(context: Context, item: CatalogItem, root: java.io.File)
|
||||
fun uninstall(context: Context, game: InstalledStoreGame)
|
||||
fun maintenanceAdapter(): com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter? = null
|
||||
}
|
||||
@@ -12,10 +12,12 @@ import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||
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.maintenance.StoreMaintenanceAdapter
|
||||
import org.json.JSONObject
|
||||
|
||||
object AmazonBackend : StoreBackend {
|
||||
override val store: Store = Store.AMAZON
|
||||
override fun maintenanceAdapter(): StoreMaintenanceAdapter = AmazonMaintenanceAdapter
|
||||
|
||||
init {
|
||||
LoginFlows.amazonFlow = { AmazonLogin.create() }
|
||||
|
||||
@@ -11,6 +11,8 @@ import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.download.StoreDownloadTier
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
@@ -20,6 +22,8 @@ internal class AmazonInstaller(
|
||||
private val app: Context,
|
||||
private val item: CatalogItem,
|
||||
private val folder: File,
|
||||
private val maintenance: JSONObject? = null,
|
||||
private val maintenanceGame: InstalledStoreGame? = null,
|
||||
) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
|
||||
@@ -29,7 +33,7 @@ internal class AmazonInstaller(
|
||||
val entitlementId = item.extra["entitlementId"].orEmpty()
|
||||
val sku = item.extra["sku"].orEmpty()
|
||||
val cover = item.tallImageUrl ?: item.imageUrl
|
||||
StoreInstalls.begin(folder, Store.AMAZON, item.id, item.title, cover, item.imageUrl)
|
||||
if (maintenance == null) StoreInstalls.begin(folder, Store.AMAZON, item.id, item.title, cover, item.imageUrl)
|
||||
if (cancelled.get()) return null
|
||||
|
||||
val tier = StoreDownloadTier.current(app)
|
||||
@@ -41,9 +45,14 @@ internal class AmazonInstaller(
|
||||
.put("maxWorkers", tier.networkWindow.coerceIn(1, 128))
|
||||
.put("processWorkers", tier.processWorkers)
|
||||
.put("caBundle", "")
|
||||
maintenance?.let {
|
||||
request.put("targetManifestPath", it.getString("manifestPath"))
|
||||
request.put("targetVersionId", it.getString("versionId"))
|
||||
}
|
||||
|
||||
val shown = AtomicLong(-1)
|
||||
val downloading = AtomicBoolean(false)
|
||||
var applyLease: AutoCloseable? = null
|
||||
val prefs = AmazonPrefs.get(app)
|
||||
val listener = object : AmazonNative.InstallListener {
|
||||
override fun onStatus(text: String) { handle.stage(DownloadStage.MANIFEST, text) }
|
||||
@@ -70,7 +79,8 @@ internal class AmazonInstaller(
|
||||
override fun onLog(line: String) { handle.log("amazon: $line") }
|
||||
|
||||
override fun beforeReplace(): Boolean = try {
|
||||
StoreInstalls.markUpdating(folder)
|
||||
if (maintenance == null) StoreInstalls.markUpdating(folder)
|
||||
else if (applyLease == null) applyLease = StoreMaintenance.beginApplyLease(maintenanceGame!!)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
handle.log("amazon: the install record could not be switched to updating (${e.javaClass.simpleName})")
|
||||
@@ -80,12 +90,11 @@ internal class AmazonInstaller(
|
||||
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) = Unit
|
||||
}
|
||||
|
||||
val outcome = AmazonNative.install(request, listener, cancelled)
|
||||
val outcome = try { AmazonNative.install(request, listener, cancelled) }
|
||||
finally { runCatching { applyLease?.close() } }
|
||||
if (outcome.cancelled || cancelled.get() && !outcome.success) return null
|
||||
if (!outcome.success) throw IllegalStateException(outcome.error.ifEmpty { "The Amazon install failed" })
|
||||
val result = outcome.result ?: JSONObject()
|
||||
|
||||
handle.stage(DownloadStage.INSTALL, "Finishing…")
|
||||
val versionId = result.optString("versionId")
|
||||
val total = result.optLong("totalBytes", 0L)
|
||||
prefs.edit().apply {
|
||||
@@ -93,6 +102,14 @@ internal class AmazonInstaller(
|
||||
putString("version_${item.id}", versionId)
|
||||
}.apply()
|
||||
|
||||
if (maintenance != null && maintenanceGame != null) {
|
||||
if (applyLease == null) StoreMaintenance.beginApplyLease(maintenanceGame).close()
|
||||
StoreMaintenance.complete(app, maintenanceGame, versionId.ifEmpty { maintenance.optString("versionId") })
|
||||
return folder.path
|
||||
}
|
||||
|
||||
handle.stage(DownloadStage.INSTALL, "Finishing…")
|
||||
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering))
|
||||
val spec = AmazonNative.call("launch.spec", JSONObject().put("gameDir", folder.absolutePath).put("title", item.title))
|
||||
?: throw IllegalStateException(AmazonNative.ENGINE_MISSING)
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.droiddeck.launcher.stores.amazon
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.SavedQueue
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
|
||||
import com.droiddeck.launcher.stores.maintenance.RecoveryState
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
|
||||
internal object AmazonMaintenanceAdapter : StoreMaintenanceAdapter {
|
||||
override val store: Store = Store.AMAZON
|
||||
private const val TARGET_SCHEMA = 1
|
||||
private const val INSTALLED_MANIFEST = ".droiddeck-maintenance/amazon/installed.manifest"
|
||||
|
||||
override fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> = buildSet {
|
||||
if (game.sidecar.extra["entitlementId"].orEmpty().isNotBlank()) add(MaintenanceAction.UPDATE)
|
||||
if (game.sidecar.installVersion.isNotBlank() && File(game.folder, INSTALLED_MANIFEST).isFile) add(MaintenanceAction.REPAIR)
|
||||
}
|
||||
|
||||
override fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck {
|
||||
val token = AmazonCredentialStore.getValidAccessToken(context)
|
||||
?: return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "Not signed in to Amazon Games")
|
||||
val entitlement = game.sidecar.extra["entitlementId"].orEmpty()
|
||||
require(entitlement.isNotBlank()) { "The installed Amazon record has no entitlement ID" }
|
||||
val latest = AmazonApiClient.getGameDownload(token, entitlement)
|
||||
?: error("Amazon's current game version could not be checked")
|
||||
if (latest.versionId.isBlank()) return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Amazon did not provide a version ID")
|
||||
val installed = game.sidecar.installVersion
|
||||
if (installed.isBlank()) return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, latest.versionId, "The installed Amazon version is unknown")
|
||||
return MaintenanceCheck(
|
||||
if (latest.versionId == installed) MaintenanceCheckState.CURRENT else MaintenanceCheckState.AVAILABLE,
|
||||
latest.versionId,
|
||||
)
|
||||
}
|
||||
|
||||
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal {
|
||||
require(action == MaintenanceAction.UPDATE || action == MaintenanceAction.REPAIR) { "Amazon supports Update and Repair" }
|
||||
require(action in capabilities(game)) { "The installed Amazon record is missing the data required for ${action.name.lowercase()}" }
|
||||
require(StoreMaintenance.readOperation(game.folder) == null) { "Resume or recover the existing Amazon operation first" }
|
||||
val token = AmazonCredentialStore.getValidAccessToken(context) ?: error("Not signed in to Amazon Games")
|
||||
val entitlement = game.sidecar.extra["entitlementId"].orEmpty()
|
||||
val current = AmazonApiClient.getGameDownload(token, entitlement) ?: error("Amazon's current download is unavailable")
|
||||
require(current.versionId.isNotBlank()) { "Amazon did not provide a version ID" }
|
||||
val dir = File(game.folder, ".droiddeck-maintenance/amazon")
|
||||
require(!Files.isSymbolicLink(File(game.folder, ".droiddeck-maintenance").toPath())) { "Amazon maintenance metadata is a symbolic link" }
|
||||
require(!Files.isSymbolicLink(dir.toPath())) { "Amazon maintenance metadata is a symbolic link" }
|
||||
dir.mkdirs()
|
||||
val (version, path, bytes) = if (action == MaintenanceAction.REPAIR) {
|
||||
require(game.sidecar.installVersion.isNotBlank()) { "The installed Amazon version is unknown; repair cannot safely choose a target" }
|
||||
val installed = File(game.folder, INSTALLED_MANIFEST)
|
||||
require(installed.isFile && !Files.isSymbolicLink(installed.toPath())) { "The installed Amazon manifest is unavailable; repair cannot safely choose a target" }
|
||||
val raw = installed.readBytes()
|
||||
val info = AmazonNative.inspect(raw) ?: error("The installed Amazon manifest could not be verified")
|
||||
require(!info.has("error")) { info.optString("error", "The installed Amazon manifest could not be verified") }
|
||||
require(info.optInt("unverifiableFiles", 0) == 0) { "Amazon's installed manifest has file hashes DroidDeck cannot verify; Repair cannot safely replace those files" }
|
||||
Triple(game.sidecar.installVersion, installed, info.optLong("totalBytes", 0L))
|
||||
} else {
|
||||
val raw = AmazonApiClient.getBytes(AmazonApiClient.appendPath(current.downloadUrl, "manifest.proto"), token)
|
||||
?: error("Amazon's update manifest could not be downloaded")
|
||||
val info = AmazonNative.inspect(raw) ?: error("Amazon's update manifest could not be read")
|
||||
require(!info.has("error")) { info.optString("error", "Amazon's update manifest could not be read") }
|
||||
require(info.optInt("unverifiableFiles", 0) == 0) { "Amazon's update manifest has file hashes DroidDeck cannot verify; it cannot safely replace those files" }
|
||||
val target = File(dir, "target.manifest")
|
||||
val temp = File(dir, "target.manifest.tmp")
|
||||
require(!Files.isSymbolicLink(temp.toPath())) { "Amazon maintenance metadata is a symbolic link" }
|
||||
temp.writeBytes(raw)
|
||||
try { Files.move(temp.toPath(), target.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
|
||||
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING) }
|
||||
Triple(current.versionId, target, info.optLong("totalBytes", 0L))
|
||||
}
|
||||
val target = JSONObject().put("schema", TARGET_SCHEMA).put("versionId", version)
|
||||
.put("manifestPath", path.absolutePath)
|
||||
return MaintenanceProposal(
|
||||
game.folder.canonicalFile, game.sidecar, "Version $version", action,
|
||||
downloadBytes = bytes, diskBytes = bytes, description = "Up to ${com.droiddeck.launcher.stores.formatBytes(bytes)} of whole-file data; existing files are verified against Amazon's manifest.",
|
||||
target = target,
|
||||
)
|
||||
}
|
||||
|
||||
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean {
|
||||
check(proposal.operation == MaintenanceAction.UPDATE || proposal.operation == MaintenanceAction.REPAIR)
|
||||
val target = validateTarget(game, proposal.target)
|
||||
return enqueueJob(context, game, target, proposal.downloadBytes, proposal.operation)
|
||||
}
|
||||
|
||||
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) {
|
||||
require(operation.optString("phase") in setOf("queued", "download", "applying")) { "The Amazon operation needs attention before it can resume" }
|
||||
val target = validateTarget(game, operation.getJSONObject("target"))
|
||||
val bytes = operation.optLong("downloadBytes", 0L).coerceAtLeast(0L)
|
||||
check(enqueueJob(context, game, target, bytes, MaintenanceAction.valueOf(operation.getString("operation")))) {
|
||||
"Amazon maintenance is already queued"
|
||||
}
|
||||
}
|
||||
|
||||
override fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
|
||||
val phase = runCatching { StoreMaintenance.readOperation(game.folder)?.optString("phase").orEmpty() }.getOrDefault("")
|
||||
return if (phase in setOf("queued", "download", "applying")) MaintenanceRecovery(RecoveryState.RESUMABLE, phase)
|
||||
else if (phase.isNotEmpty()) MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, phase) else MaintenanceRecovery()
|
||||
}
|
||||
|
||||
private fun validateTarget(game: InstalledStoreGame, target: JSONObject): JSONObject {
|
||||
require(target.optInt("schema") == TARGET_SCHEMA) { "The saved Amazon maintenance target is unsupported" }
|
||||
require(target.optString("versionId").isNotBlank()) { "The saved Amazon target has no version ID" }
|
||||
val rawPath = File(target.optString("manifestPath"))
|
||||
require(!Files.isSymbolicLink(rawPath.toPath())) { "The saved Amazon manifest is a symbolic link" }
|
||||
val path = rawPath.canonicalFile
|
||||
require(path.path.startsWith(game.folder.canonicalPath + File.separator) && path.isFile) {
|
||||
"The saved Amazon manifest is unavailable or outside the install folder"
|
||||
}
|
||||
val checked = AmazonNative.inspect(path.readBytes()) ?: error("The saved Amazon manifest could not be verified")
|
||||
require(!checked.has("error")) { checked.optString("error", "The saved Amazon manifest could not be verified") }
|
||||
require(checked.optInt("unverifiableFiles", 0) == 0) { "Amazon's saved manifest has file hashes DroidDeck cannot verify; it cannot safely replace those files" }
|
||||
return JSONObject(target.toString()).put("manifestPath", path.absolutePath)
|
||||
}
|
||||
|
||||
private fun enqueueJob(context: Context, game: InstalledStoreGame, target: JSONObject, bytes: Long, action: MaintenanceAction): Boolean {
|
||||
val app = context.applicationContext
|
||||
val sidecar = game.sidecar
|
||||
val item = CatalogItem(Store.AMAZON, sidecar.id, sidecar.title, sidecar.hero, tallImageUrl = sidecar.cover,
|
||||
extra = mapOf("entitlementId" to sidecar.extra["entitlementId"].orEmpty(), "sku" to sidecar.extra["sku"].orEmpty(),
|
||||
StoreMaintenance.OPERATION_KEY to action.name, StoreMaintenance.FOLDER_KEY to game.folder.absolutePath))
|
||||
return DownloadQueue.enqueueIfIdle(app, DownloadEntry(Store.AMAZON, item.id, item.title, cover = item.tallImageUrl,
|
||||
bytesTotal = bytes, location = StoreInstallRoot.labelFor(app, game.folder)), onAccepted = {
|
||||
SavedQueue.remember(app, item, null)
|
||||
}) {
|
||||
AmazonInstaller(app, item, game.folder, target, game)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,8 @@ 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.DownloadStage
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
@@ -176,6 +178,18 @@ object BattleNetInstall {
|
||||
|
||||
fun checkUpdate(context: Context, game: InstalledStoreGame, force: Boolean = false) = check(game.sidecar.id, game.folder, force)
|
||||
|
||||
fun maintenanceCheck(context: Context, game: InstalledStoreGame): MaintenanceCheck {
|
||||
val product = product(game.sidecar.id)
|
||||
?: return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Battle.net does not support this installed product")
|
||||
val local = runCatching { buildKey(File(game.folder, BUILD_INFO).readText()) }.getOrNull()
|
||||
?: return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "The installed Battle.net build is unknown")
|
||||
val latest = runCatching { latestBuild(fetch(VERSIONS.format(Locale.ROOT, local.first, product)), local.first) }
|
||||
.getOrElse { return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = it.message ?: "Battle.net update check failed") }
|
||||
?: return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Battle.net did not provide a build for region ${local.first}")
|
||||
return if (latest == local.second) MaintenanceCheck(MaintenanceCheckState.CURRENT, latest)
|
||||
else MaintenanceCheck(MaintenanceCheckState.AVAILABLE, latest)
|
||||
}
|
||||
|
||||
internal fun check(id: String, folder: File, force: Boolean) {
|
||||
val product = product(id) ?: return
|
||||
val now = System.currentTimeMillis()
|
||||
@@ -271,8 +285,9 @@ internal class BattleNetInstaller(
|
||||
var reason: String? = null
|
||||
val code = BattleNetInstall.run(app, args, cancelled) { line ->
|
||||
when {
|
||||
line.startsWith(BattleNetInstall.PROGRESS) ->
|
||||
runCatching { JSONObject(line.removePrefix(BattleNetInstall.PROGRESS)) }.getOrNull()?.let { progress(handle, it) }
|
||||
line.startsWith(BattleNetInstall.PROGRESS) -> runCatching { JSONObject(line.removePrefix(BattleNetInstall.PROGRESS)) }.getOrNull()?.let {
|
||||
progress(handle, it)
|
||||
}
|
||||
line == BattleNetInstall.STATE + "waiting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_waiting))
|
||||
line == BattleNetInstall.STATE + "queued" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_queued))
|
||||
line == BattleNetInstall.STATE + "starting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_starting))
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.droiddeck.launcher.stores.battlenet
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
|
||||
import com.droiddeck.launcher.stores.maintenance.RecoveryState
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
|
||||
import org.json.JSONObject
|
||||
|
||||
internal object BattleNetMaintenanceAdapter : StoreMaintenanceAdapter {
|
||||
override val store = Store.BATTLENET
|
||||
|
||||
override fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> = setOf(MaintenanceAction.OPEN_CLIENT)
|
||||
|
||||
override fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck =
|
||||
BattleNetInstall.maintenanceCheck(context, game)
|
||||
|
||||
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal =
|
||||
error("Battle.net updates must use its Agent/client workflow")
|
||||
|
||||
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean =
|
||||
error("Battle.net updates must use its Agent/client workflow")
|
||||
|
||||
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject): Unit =
|
||||
error("Resume this Battle.net operation through its Agent/client workflow")
|
||||
|
||||
override fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
|
||||
if (StoreMaintenance.readOperation(game.folder) == null) return MaintenanceRecovery()
|
||||
return MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, "Inspect this update in Battle.net before launching the game")
|
||||
}
|
||||
|
||||
override fun openClient(context: Context, game: InstalledStoreGame) = BattleNetClient.open(emptyList())
|
||||
|
||||
override fun openClientLabel(game: InstalledStoreGame) = "Open Battle.net for Scan and Repair"
|
||||
}
|
||||
@@ -19,6 +19,7 @@ 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.DownloadStage
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
@@ -153,6 +154,7 @@ object BattleNetClient {
|
||||
|
||||
object BattleNetBackend : StoreBackend {
|
||||
override val store: Store = Store.BATTLENET
|
||||
override fun maintenanceAdapter(): StoreMaintenanceAdapter = BattleNetMaintenanceAdapter
|
||||
|
||||
override fun signIn(context: Context) = BattleNetClient.signIn(context)
|
||||
|
||||
|
||||
@@ -31,6 +31,9 @@ data class DownloadEntry(
|
||||
val stageItemsTotal: Int = 0,
|
||||
val diskBytes: Long = 0L,
|
||||
val stagesPassed: Int = 0,
|
||||
val interruptible: Boolean = true,
|
||||
val reusedBytes: Long = 0L,
|
||||
val appliedBytes: Long = 0L,
|
||||
) {
|
||||
fun passed(s: DownloadStage): Boolean = state == DownloadState.INSTALLED || (stagesPassed and (1 shl s.ordinal)) != 0
|
||||
|
||||
|
||||
@@ -21,6 +21,11 @@ object DownloadQueue {
|
||||
fun diskSize(bytes: Long) = update(key) { if (bytes > 0) it.copy(diskBytes = bytes) else it }
|
||||
fun progress(bytesDone: Long, bytesTotal: Long, detail: String? = null, @Suppress("UNUSED_PARAMETER") speedBps: Long = -1L) = measure(key, bytesDone, bytesTotal, detail?.let(::stripSpeed))
|
||||
fun log(line: String) = StoresState.logLine(line)
|
||||
fun interruptible(value: Boolean) = update(key) {
|
||||
check(value || !cancelled.get()) { "The operation was paused before installer application" }
|
||||
it.copy(interruptible = value)
|
||||
}
|
||||
fun maintenance(reusedBytes: Long, appliedBytes: Long) = update(key) { it.copy(reusedBytes = reusedBytes, appliedBytes = appliedBytes) }
|
||||
}
|
||||
|
||||
private fun stripSpeed(s: String): String = s.replace(Regex("\\s+\\S+ [KMG]B/s\\s*$"), "").trimEnd()
|
||||
@@ -124,9 +129,32 @@ object DownloadQueue {
|
||||
fun isActive(key: String): Boolean = entry(key)?.isActive == true
|
||||
|
||||
fun enqueue(context: Context, entry: DownloadEntry, factory: () -> DownloadJob) {
|
||||
enqueueInternal(context, entry, onAccepted = {}, factory = factory)
|
||||
}
|
||||
|
||||
/** Enqueues only if the key is idle, running [onAccepted] atomically before the accepted row is saved. */
|
||||
fun enqueueIfIdle(
|
||||
context: Context,
|
||||
entry: DownloadEntry,
|
||||
onAccepted: () -> Unit,
|
||||
factory: () -> DownloadJob,
|
||||
): Boolean = enqueueInternal(context, entry, onAccepted = onAccepted, factory = factory)
|
||||
|
||||
private fun enqueueInternal(
|
||||
context: Context,
|
||||
entry: DownloadEntry,
|
||||
onAccepted: () -> Unit,
|
||||
factory: () -> DownloadJob,
|
||||
): Boolean {
|
||||
val app = context.applicationContext
|
||||
synchronized(lock) {
|
||||
items[entry.key]?.let { if (it.entry.isActive) { Log.i(TAG, "${entry.key}: already queued"); return } }
|
||||
items[entry.key]?.let {
|
||||
if (it.entry.isActive) {
|
||||
Log.i(TAG, "${entry.key}: already queued")
|
||||
return false
|
||||
}
|
||||
}
|
||||
onAccepted()
|
||||
items.remove(entry.key)
|
||||
val state = if (heldPaused.remove(entry.key)) DownloadState.PAUSED else DownloadState.QUEUED
|
||||
items[entry.key] = Item(entry.copy(state = state, stage = DownloadStage.MANIFEST, startedAt = System.currentTimeMillis()), factory)
|
||||
@@ -135,6 +163,7 @@ object DownloadQueue {
|
||||
StoresState.logLine("${entry.store.label}: queued \"${entry.name}\"" + if (entry.bytesTotal > 0) " (${com.droiddeck.launcher.stores.formatBytes(entry.bytesTotal)})" else "")
|
||||
publish(app)
|
||||
advance(app)
|
||||
return true
|
||||
}
|
||||
|
||||
/** Immediately records a failed download (e.g. from pre-flight storage check). */
|
||||
@@ -166,12 +195,13 @@ object DownloadQueue {
|
||||
fun pause(key: String) {
|
||||
val item = synchronized(lock) { items[key] } ?: return
|
||||
synchronized(lock) {
|
||||
if (!item.entry.interruptible) return
|
||||
if (item.entry.state == DownloadState.QUEUED) { item.entry = item.entry.copy(state = DownloadState.PAUSED, queuePosition = 0); renumber(); publishLocked(); return }
|
||||
if (item.entry.state != DownloadState.RUNNING) return
|
||||
item.pauseRequested = true
|
||||
item.cancelled.set(true)
|
||||
item.job?.cancel(deleteFiles = false)
|
||||
}
|
||||
item.cancelled.set(true)
|
||||
item.job?.cancel(deleteFiles = false)
|
||||
StoresState.logLine("paused \"${item.entry.name}\"")
|
||||
}
|
||||
|
||||
@@ -204,17 +234,19 @@ object DownloadQueue {
|
||||
val wasRunning: Boolean
|
||||
synchronized(lock) {
|
||||
item = items[key] ?: return
|
||||
if (!item.entry.interruptible) return
|
||||
wasRunning = item.entry.state == DownloadState.RUNNING
|
||||
if (wasRunning) {
|
||||
item.cancelled.set(true)
|
||||
item.job?.cancel(deleteFiles = true)
|
||||
}
|
||||
if (!wasRunning) {
|
||||
item.entry = item.entry.copy(state = DownloadState.CANCELLED, queuePosition = 0, finishedAt = System.currentTimeMillis())
|
||||
renumber()
|
||||
publishLocked()
|
||||
}
|
||||
}
|
||||
if (wasRunning) {
|
||||
item.cancelled.set(true)
|
||||
item.job?.cancel(deleteFiles = true)
|
||||
} else {
|
||||
if (!wasRunning) {
|
||||
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-cancel").start()
|
||||
}
|
||||
StoresState.logLine("cancelled \"${item.entry.name}\"")
|
||||
|
||||
@@ -45,7 +45,7 @@ object SavedQueue {
|
||||
val f = File(context.filesDir, FILE)
|
||||
val tmp = File(context.filesDir, "$FILE.tmp")
|
||||
tmp.writeText(out.toString())
|
||||
tmp.renameTo(f)
|
||||
java.nio.file.Files.move(tmp.toPath(), f.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
}.onFailure { Log.w(TAG, "could not save the queue", it) }
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,13 @@ object SavedQueue {
|
||||
for ((item, root, paused) in back) {
|
||||
if (DownloadQueue.entry(key(item)) != null) continue
|
||||
if (paused) DownloadQueue.holdPaused(key(item))
|
||||
StoresState.install(app, item, root)
|
||||
if (item.extra.containsKey(com.droiddeck.launcher.stores.maintenance.StoreMaintenance.OPERATION_KEY) ||
|
||||
item.store == Store.GOG && item.extra.containsKey(com.droiddeck.launcher.stores.gog.GogMaintenance.OPERATION)) {
|
||||
Thread({
|
||||
runCatching { com.droiddeck.launcher.stores.maintenance.StoreMaintenance.restore(app, item) }
|
||||
.onFailure { DownloadQueue.recordFailed(app, DownloadEntry(item.store, item.id, item.title), it.message ?: "${item.store.label} recovery failed") }
|
||||
}, "store-maintenance-restore").start()
|
||||
} else StoresState.install(app, item, root)
|
||||
}
|
||||
}
|
||||
}, "store-queue-restore").start()
|
||||
|
||||
@@ -14,10 +14,12 @@ import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||
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.maintenance.StoreMaintenanceAdapter
|
||||
import com.droiddeck.launcher.stores.mergeItems
|
||||
|
||||
object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
override val store: Store = Store.EPIC
|
||||
override fun maintenanceAdapter(): StoreMaintenanceAdapter = EpicMaintenanceAdapter
|
||||
|
||||
init {
|
||||
LoginFlows.epicFlow = { EpicLogin.create() }
|
||||
|
||||
@@ -13,6 +13,8 @@ import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.download.StoreDownloadTier
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
@@ -23,6 +25,8 @@ internal class EpicInstaller(
|
||||
private val app: Context,
|
||||
private val item: CatalogItem,
|
||||
private val folder: File,
|
||||
private val maintenance: JSONObject? = null,
|
||||
private val maintenanceGame: InstalledStoreGame? = null,
|
||||
) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
private val namespace = item.extra["namespace"].orEmpty()
|
||||
@@ -36,7 +40,14 @@ internal class EpicInstaller(
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_sync_sign_in))
|
||||
val token = EpicCredentialStore.getValidAccessToken(app) ?: throw IllegalStateException("Not signed in to Epic Games")
|
||||
val cover = item.tallImageUrl ?: item.imageUrl
|
||||
StoreInstalls.begin(folder, Store.EPIC, item.id, item.title, cover, item.imageUrl)
|
||||
val tags = maintenance?.optJSONArray("tags")?.let { a -> List(a.length()) { a.optString(it) } }
|
||||
?: EpicInstallTags.tagsFor(installLocale())
|
||||
val priorTagsRaw = maintenanceGame?.sidecar?.extra?.get("installTags")
|
||||
?: StoreGameSidecar.read(folder)?.extra?.get("installTags").orEmpty()
|
||||
val previousTags = runCatching {
|
||||
if (priorTagsRaw.isBlank()) tags else JSONArray(priorTagsRaw).let { a -> List(a.length()) { a.optString(it) } }
|
||||
}.getOrDefault(tags)
|
||||
if (maintenance == null) StoreInstalls.begin(folder, Store.EPIC, item.id, item.title, cover, item.imageUrl)
|
||||
if (cancelled.get()) return null
|
||||
|
||||
handle.stage(DownloadStage.MANIFEST, "Reading the build list…")
|
||||
@@ -50,13 +61,16 @@ internal class EpicInstaller(
|
||||
.put("gameDir", folder.absolutePath)
|
||||
.put("scratchDir", if (StoreInstallRoot.isRemovable(app, folder)) scratch().absolutePath else "")
|
||||
.put("storageLabel", StoreInstallRoot.labelFor(app, folder))
|
||||
.put("tags", JSONArray(EpicInstallTags.tagsFor(installLocale())))
|
||||
.put("tags", JSONArray(tags))
|
||||
.put("previousTags", JSONArray(previousTags))
|
||||
.put("maxWorkers", tier.networkWindow.coerceIn(1, 128))
|
||||
.put("processWorkers", tier.processWorkers)
|
||||
.put("caBundle", "")
|
||||
maintenance?.let { request.put("targetManifestPath", it.getString("manifestPath")) }
|
||||
|
||||
val shown = AtomicLong(-1)
|
||||
val installing = AtomicBoolean(false)
|
||||
var applyLease: AutoCloseable? = null
|
||||
val prefs = EpicPrefs.get(app)
|
||||
val listener = object : EpicNative.InstallListener {
|
||||
override fun onStatus(text: String) { handle.stage(DownloadStage.MANIFEST, text) }
|
||||
@@ -90,7 +104,8 @@ internal class EpicInstaller(
|
||||
override fun onLog(line: String) { handle.log("epic: $line") }
|
||||
|
||||
override fun beforeReplace(): Boolean = try {
|
||||
StoreInstalls.markUpdating(folder)
|
||||
if (maintenance == null) StoreInstalls.markUpdating(folder)
|
||||
else if (applyLease == null) applyLease = StoreMaintenance.beginApplyLease(maintenanceGame!!)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
handle.log("epic: the install record could not be switched to updating (${e.javaClass.simpleName})")
|
||||
@@ -100,11 +115,21 @@ internal class EpicInstaller(
|
||||
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) = Unit
|
||||
}
|
||||
|
||||
val outcome = EpicNative.install(request, listener, cancelled)
|
||||
val outcome = try { EpicNative.install(request, listener, cancelled) }
|
||||
finally { runCatching { applyLease?.close() } }
|
||||
if (outcome.cancelled || cancelled.get() && !outcome.success) return null
|
||||
if (!outcome.success) throw IllegalStateException(outcome.error.ifEmpty { "Native Epic install failed" })
|
||||
val result = outcome.result ?: JSONObject()
|
||||
|
||||
if (maintenance != null && maintenanceGame != null) {
|
||||
if (applyLease == null) StoreMaintenance.beginApplyLease(maintenanceGame).close()
|
||||
val extra = LinkedHashMap(maintenanceGame.sidecar.extra)
|
||||
maintenance.optString("deploymentId").takeIf { it.isNotBlank() }?.let { extra["deploymentId"] = it }
|
||||
maintenance.optString("buildInfoVersion").takeIf { it.isNotBlank() }?.let { extra["buildInfoVersion"] = it }
|
||||
StoreMaintenance.complete(app, maintenanceGame, result.optString("buildVersion"), extra)
|
||||
return folder.path
|
||||
}
|
||||
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering))
|
||||
val picked = StoreExe.pick(folder, result.optString("launchExe"), item.title)
|
||||
if (picked.isEmpty()) handle.log("epic: no exe found in ${folder.name}; pick one in Steam settings › Added games")
|
||||
@@ -125,7 +150,9 @@ internal class EpicInstaller(
|
||||
extra["namespace"] = namespace
|
||||
extra["catalogItemId"] = catalogItemId
|
||||
if (deployment.isNotEmpty()) extra["deploymentId"] = deployment
|
||||
extra["buildInfoVersion"] = JSONObject(info).optString("buildVersion")
|
||||
extra[StoreLanguage.EXTRA] = item.extra[StoreLanguage.EXTRA] ?: StoreLanguage.preferredCode(app)
|
||||
extra["installTags"] = JSONArray(EpicInstallTags.tagsFor(installLocale())).toString()
|
||||
extra[WinCompSources.EPIC_PREREQ_PATH] = result.optString("prereqPath")
|
||||
extra[WinCompSources.EPIC_PREREQ_NAME] = result.optString("prereqName")
|
||||
if (result.optBoolean("prereqRead", false)) extra[WinCompSources.LIST_READ] = "1"
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.SavedQueue
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
|
||||
import com.droiddeck.launcher.stores.maintenance.RecoveryState
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
|
||||
internal object EpicMaintenanceAdapter : StoreMaintenanceAdapter {
|
||||
override val store: Store = Store.EPIC
|
||||
private const val TARGET_SCHEMA = 1
|
||||
private const val INSTALLED_MANIFEST = ".droiddeck-maintenance/epic/installed.manifest"
|
||||
|
||||
override fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> = buildSet {
|
||||
val extra = game.sidecar.extra
|
||||
if (extra["namespace"].orEmpty().isNotBlank() && extra["catalogItemId"].orEmpty().isNotBlank()) add(MaintenanceAction.UPDATE)
|
||||
if (game.sidecar.installVersion.isNotBlank() && File(game.folder, INSTALLED_MANIFEST).isFile) add(MaintenanceAction.REPAIR)
|
||||
}
|
||||
|
||||
override fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck {
|
||||
val token = EpicCredentialStore.getValidAccessToken(context)
|
||||
?: return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "Not signed in to Epic Games")
|
||||
val info = currentInfo(token, game.sidecar.id, game.sidecar.extra)
|
||||
val latest = info.optString("buildVersion")
|
||||
if (latest.isBlank()) return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Epic did not provide a build version")
|
||||
val installed = game.sidecar.extra["buildInfoVersion"].orEmpty().ifBlank { game.sidecar.installVersion }
|
||||
if (installed.isBlank()) return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, latest, "The installed Epic build is unknown")
|
||||
return MaintenanceCheck(if (latest == installed) MaintenanceCheckState.CURRENT else MaintenanceCheckState.AVAILABLE, latest)
|
||||
}
|
||||
|
||||
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal {
|
||||
require(action == MaintenanceAction.UPDATE || action == MaintenanceAction.REPAIR) { "Epic supports Update and Repair" }
|
||||
require(action in capabilities(game)) { "The installed Epic record is missing the data required for ${action.name.lowercase()}" }
|
||||
require(StoreMaintenance.readOperation(game.folder) == null) { "Resume or recover the existing Epic operation first" }
|
||||
val token = EpicCredentialStore.getValidAccessToken(context) ?: error("Not signed in to Epic Games")
|
||||
val info = currentInfo(token, game.sidecar.id, game.sidecar.extra)
|
||||
val tags = installedTags(context, game)
|
||||
val buildInfoVersion = info.optString("buildVersion").ifBlank { error("Epic did not provide a build version") }
|
||||
val dir = File(game.folder, ".droiddeck-maintenance/epic")
|
||||
require(!Files.isSymbolicLink(File(game.folder, ".droiddeck-maintenance").toPath()) && !Files.isSymbolicLink(dir.toPath())) {
|
||||
"Epic maintenance metadata is a symbolic link"
|
||||
}
|
||||
dir.mkdirs()
|
||||
val targetPath: File
|
||||
val manifestBytes: ByteArray
|
||||
val targetBuild: String
|
||||
val deploymentId: String
|
||||
if (action == MaintenanceAction.REPAIR) {
|
||||
targetPath = File(game.folder, INSTALLED_MANIFEST)
|
||||
require(targetPath.isFile && !Files.isSymbolicLink(targetPath.toPath())) { "The installed Epic manifest is unavailable; repair cannot safely choose a target" }
|
||||
manifestBytes = targetPath.readBytes()
|
||||
val parsed = EpicNative.inspect(manifestBytes, JSONObject()) ?: error("The installed Epic manifest could not be read")
|
||||
require(!parsed.has("error")) { parsed.optString("error", "The installed Epic manifest could not be read") }
|
||||
targetBuild = parsed.optString("buildVersion").ifBlank { error("The installed Epic manifest has no build version") }
|
||||
deploymentId = game.sidecar.extra["deploymentId"].orEmpty()
|
||||
} else {
|
||||
manifestBytes = EpicNative.fetch("manifest.download", JSONObject().put("info", info))
|
||||
?: error("Epic's update manifest could not be downloaded")
|
||||
val parsed = EpicNative.inspect(manifestBytes, JSONObject()) ?: error("Epic's update manifest could not be read")
|
||||
require(!parsed.has("error")) { parsed.optString("error", "Epic's update manifest could not be read") }
|
||||
targetBuild = parsed.optString("buildVersion").ifBlank { buildInfoVersion }
|
||||
deploymentId = info.optString("deploymentId")
|
||||
targetPath = File(dir, "target.manifest")
|
||||
val temp = File(dir, "target.manifest.tmp")
|
||||
require(!Files.isSymbolicLink(temp.toPath())) { "Epic maintenance metadata is a symbolic link" }
|
||||
temp.writeBytes(manifestBytes)
|
||||
try { Files.move(temp.toPath(), targetPath.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
|
||||
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(temp.toPath(), targetPath.toPath(), StandardCopyOption.REPLACE_EXISTING) }
|
||||
}
|
||||
val estimate = EpicNative.inspect(manifestBytes, JSONObject().put("op", "estimate").put("tags", JSONArray(tags)))
|
||||
?: error("Epic's target manifest could not be checked")
|
||||
require(!estimate.has("error")) { estimate.optString("error", "Epic's target manifest could not be checked") }
|
||||
val downloadBytes = estimate.optLong("downloadBytes", -1L)
|
||||
val diskBytes = estimate.optLong("diskBytes", -1L)
|
||||
require(downloadBytes >= 0 && diskBytes >= 0) { "Epic's target manifest has an invalid size estimate" }
|
||||
val target = JSONObject().put("schema", TARGET_SCHEMA).put("buildVersion", targetBuild)
|
||||
.put("buildInfoVersion", if (action == MaintenanceAction.REPAIR) game.sidecar.extra["buildInfoVersion"].orEmpty() else buildInfoVersion)
|
||||
.put("deploymentId", deploymentId)
|
||||
.put("manifestPath", targetPath.absolutePath).put("tags", JSONArray(tags))
|
||||
return MaintenanceProposal(
|
||||
game.folder.canonicalFile, game.sidecar,
|
||||
if (action == MaintenanceAction.REPAIR) "Installed build $targetBuild" else "Build $targetBuild", action,
|
||||
downloadBytes = downloadBytes, diskBytes = diskBytes,
|
||||
description = "Up to ${com.droiddeck.launcher.stores.formatBytes(downloadBytes)} of unique Epic chunks; files are SHA-1 verified against the pinned manifest.",
|
||||
target = target,
|
||||
)
|
||||
}
|
||||
|
||||
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean {
|
||||
check(proposal.operation == MaintenanceAction.UPDATE || proposal.operation == MaintenanceAction.REPAIR)
|
||||
val target = validateTarget(game, proposal.target)
|
||||
return enqueueJob(context, game, target, proposal.downloadBytes, proposal.operation)
|
||||
}
|
||||
|
||||
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) {
|
||||
require(operation.optString("phase") in setOf("queued", "download", "applying")) { "The Epic operation needs attention before it can resume" }
|
||||
val target = validateTarget(game, operation.getJSONObject("target"))
|
||||
check(enqueueJob(context, game, target, operation.optLong("downloadBytes", 0L).coerceAtLeast(0L),
|
||||
MaintenanceAction.valueOf(operation.getString("operation")))) { "Epic maintenance is already queued" }
|
||||
}
|
||||
|
||||
override fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
|
||||
val phase = runCatching { StoreMaintenance.readOperation(game.folder)?.optString("phase").orEmpty() }.getOrDefault("")
|
||||
return if (phase in setOf("queued", "download", "applying")) MaintenanceRecovery(RecoveryState.RESUMABLE, phase)
|
||||
else if (phase.isNotEmpty()) MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, phase) else MaintenanceRecovery()
|
||||
}
|
||||
|
||||
private fun validateTarget(game: InstalledStoreGame, target: JSONObject): JSONObject {
|
||||
require(target.optInt("schema") == TARGET_SCHEMA) { "The saved Epic maintenance target is unsupported" }
|
||||
require(target.optString("buildVersion").isNotBlank()) { "The saved Epic target has no build version" }
|
||||
val rawPath = File(target.optString("manifestPath"))
|
||||
require(!Files.isSymbolicLink(rawPath.toPath())) { "The saved Epic manifest is a symbolic link" }
|
||||
val path = rawPath.canonicalFile
|
||||
require(path.path.startsWith(game.folder.canonicalPath + File.separator) && path.isFile) {
|
||||
"The saved Epic manifest is unavailable or outside the install folder"
|
||||
}
|
||||
val parsed = EpicNative.inspect(path.readBytes(), JSONObject()) ?: error("The saved Epic manifest could not be verified")
|
||||
require(!parsed.has("error") && parsed.optString("buildVersion") == target.optString("buildVersion")) {
|
||||
"The saved Epic manifest does not match the pinned build"
|
||||
}
|
||||
return JSONObject(target.toString()).put("manifestPath", path.absolutePath)
|
||||
}
|
||||
|
||||
private fun currentInfo(token: String, id: String, extra: Map<String, String>): JSONObject {
|
||||
val namespace = extra["namespace"].orEmpty().ifBlank { error("The Epic namespace is missing from the install record") }
|
||||
val catalog = extra["catalogItemId"].orEmpty().ifBlank { error("The Epic catalog item ID is missing from the install record") }
|
||||
val raw = EpicApiClient.getManifestApiJson(token, namespace, catalog, extra["appName"] ?: id)
|
||||
?: error("Epic's current build information could not be fetched")
|
||||
return JSONObject(raw)
|
||||
}
|
||||
|
||||
private fun installedTags(context: Context, game: InstalledStoreGame): List<String> = runCatching {
|
||||
val raw = game.sidecar.extra["installTags"].orEmpty()
|
||||
val array = JSONArray(raw)
|
||||
List(array.length()) { array.getString(it) }.filter { it.isNotBlank() }
|
||||
}.getOrElse {
|
||||
EpicInstallTags.tagsFor(StoreLanguage.localeFor(game.sidecar.extra[StoreLanguage.EXTRA], context))
|
||||
}
|
||||
|
||||
private fun enqueueJob(context: Context, game: InstalledStoreGame, target: JSONObject, bytes: Long, action: MaintenanceAction): Boolean {
|
||||
val app = context.applicationContext
|
||||
val sidecar = game.sidecar
|
||||
val extra = LinkedHashMap(sidecar.extra)
|
||||
val item = CatalogItem(Store.EPIC, sidecar.id, sidecar.title, sidecar.hero, tallImageUrl = sidecar.cover,
|
||||
extra = extra + mapOf(StoreMaintenance.OPERATION_KEY to action.name, StoreMaintenance.FOLDER_KEY to game.folder.absolutePath))
|
||||
return DownloadQueue.enqueueIfIdle(app, DownloadEntry(Store.EPIC, item.id, item.title, cover = item.tallImageUrl,
|
||||
bytesTotal = bytes, location = StoreInstallRoot.labelFor(app, game.folder)), onAccepted = {
|
||||
SavedQueue.remember(app, item, null)
|
||||
}) {
|
||||
EpicInstaller(app, item, game.folder, target, game)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ object GogAuth {
|
||||
|
||||
@Synchronized
|
||||
private fun saveAccount(context: Context, accessToken: String, refreshToken: String?, userId: String?) {
|
||||
GogMaintenance.reset()
|
||||
var username = ""
|
||||
runCatching {
|
||||
val body = StoreNet.get("https://embed.gog.com/userData.json", bearer = accessToken, userAgent = GALAXY_UA)
|
||||
|
||||
@@ -28,6 +28,7 @@ object GogBackend : StoreBackend {
|
||||
}
|
||||
|
||||
override fun signOut(context: Context) {
|
||||
GogMaintenance.reset()
|
||||
GogPrefs.get(context).edit().remove("library_cache").remove("library_cache_v2").remove("library_synced_at").apply()
|
||||
}
|
||||
|
||||
@@ -53,7 +54,11 @@ object GogBackend : StoreBackend {
|
||||
StoresState.post {
|
||||
StoresState.status.remove(store)
|
||||
when (result) {
|
||||
is GogLibrary.SyncResult.Ok -> { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store) }
|
||||
is GogLibrary.SyncResult.Ok -> {
|
||||
StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) })
|
||||
StoresState.problems.remove(store)
|
||||
GogMaintenance.checkInstalled(app, StoresState.installed)
|
||||
}
|
||||
is GogLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
|
||||
GogLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
|
||||
GogLibrary.SyncResult.Busy -> {}
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.zip.GZIPInputStream
|
||||
import java.util.zip.InflaterInputStream
|
||||
|
||||
internal object GogContent {
|
||||
const val SYSTEM = "https://content-system.gog.com"
|
||||
const val CDN = "https://gog-cdn-fastly.gog.com/content-system"
|
||||
|
||||
fun token(context: Context) = GogAuth.validToken(context) ?: error("Sign in to GOG and retry")
|
||||
|
||||
fun builds(id: String, token: String): JSONObject {
|
||||
val result = json("$SYSTEM/products/$id/os/windows/builds?generation=2", token)
|
||||
if (result.optJSONArray("items")?.length() != 0) return result
|
||||
return json("$SYSTEM/products/$id/os/windows/builds?generation=1", token)
|
||||
}
|
||||
|
||||
fun product(id: String, token: String): JSONObject = json("https://api.gog.com/products/$id?expand=downloads", token)
|
||||
|
||||
fun downloadFilename(url: String): String = java.net.URLDecoder.decode(URL(url).path.substringAfterLast('/').replace("+", "%2B"), "UTF-8")
|
||||
|
||||
fun resolveDownload(download: GogOfflineDownload, token: String): GogOfflineDownload = download.copy(parts = download.parts.map { part ->
|
||||
val resolved = GogDownloadManager.resolveRedirect(part.url, token) ?: error("The GOG download link is unavailable")
|
||||
val connection = URL(resolved).openConnection() as HttpURLConnection
|
||||
try {
|
||||
connection.requestMethod = "HEAD"
|
||||
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
|
||||
check(connection.responseCode in 200..299) { "GOG download metadata failed (HTTP ${connection.responseCode})" }
|
||||
val disposition = connection.getHeaderField("Content-Disposition").orEmpty()
|
||||
val supplied = Regex("filename=\"?([^\";]+)", RegexOption.IGNORE_CASE).find(disposition)?.groupValues?.get(1).orEmpty()
|
||||
val remote = downloadFilename(resolved).takeIf { it.endsWith(".exe", true) || it.endsWith(".bin", true) }.orEmpty()
|
||||
val name = part.name.ifBlank { supplied.ifBlank { remote } }
|
||||
check(name.isNotBlank()) { "GOG did not provide the installer part filename" }
|
||||
part.copy(name = name, size = connection.contentLengthLong.coerceAtLeast(0))
|
||||
} finally { connection.disconnect() }
|
||||
})
|
||||
|
||||
fun json(url: String, token: String? = null): JSONObject {
|
||||
require(URL(url).protocol == "https") { "GOG metadata requires HTTPS" }
|
||||
val connection = URL(url).openConnection() as HttpURLConnection
|
||||
try {
|
||||
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
|
||||
connection.setRequestProperty("User-Agent", GogAuth.GALAXY_UA)
|
||||
if (token != null && URL(url).host.let { it == "gog.com" || it.endsWith(".gog.com") }) connection.setRequestProperty("Authorization", "Bearer $token")
|
||||
check(connection.responseCode in 200..299) { "GOG metadata request failed (HTTP ${connection.responseCode})" }
|
||||
val raw = connection.inputStream.readBytes()
|
||||
val text = when {
|
||||
raw.size > 1 && raw[0] == 0x78.toByte() -> InflaterInputStream(raw.inputStream()).bufferedReader().use { it.readText() }
|
||||
raw.size > 1 && raw[0] == 0x1f.toByte() && raw[1] == 0x8b.toByte() -> GZIPInputStream(raw.inputStream()).bufferedReader().use { it.readText() }
|
||||
else -> raw.toString(Charsets.UTF_8)
|
||||
}
|
||||
return JSONObject(text)
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
|
||||
fun snapshot(old: GogInstallRecord, build: GogBuild, token: String,
|
||||
metadata: (String, String?) -> JSONObject = ::json): GogInstallRecord {
|
||||
check(build.link.isNotBlank()) { "GOG build manifest is unavailable" }
|
||||
val manifest = metadata(build.link, token)
|
||||
val files = JSONArray()
|
||||
val depots = if (build.generation == 1) manifest.optJSONObject("product")?.optJSONArray("depots") ?: manifest.optJSONArray("depot") else manifest.optJSONArray("depots")
|
||||
check(depots != null) { "GOG build has no depot list" }
|
||||
val resolvedLanguage = StoreLanguage.pick(StoreLanguage.codesFromDepots(depots), old.language)
|
||||
val selectedBitness = if (depots.objects().any { it.optJSONArray("osBitness")?.strings()?.contains("64") == true }) "64" else "32"
|
||||
val owned = if (old.products.any { it != old.id }) StoreNet.get("https://embed.gog.com/user/data/games", bearer = token)?.let { JSONObject(it).optJSONArray("owned")?.strings()?.toSet() } else emptySet()
|
||||
val products = old.products.filter { it == old.id || owned?.contains(it) == true }
|
||||
check(old.products.all { it == old.id || owned?.contains(it) == true }) { "Could not confirm ownership of installed GOG DLC" }
|
||||
for (depot in depots.objects()) {
|
||||
if (depot.has("redist")) continue
|
||||
val ids = depot.optJSONArray("gameIDs")?.strings() ?: listOf(depot.optString("productId", old.id))
|
||||
val product = ids.firstOrNull { it in products } ?: continue
|
||||
val languages = depot.optJSONArray("languages")?.strings().orEmpty()
|
||||
if (!languageSelected(languages, resolvedLanguage)) continue
|
||||
val bitness = depot.optJSONArray("osBitness")?.strings().orEmpty()
|
||||
if (bitness.isNotEmpty() && selectedBitness !in bitness) continue
|
||||
val hash = depot.optString("manifest")
|
||||
val content = when {
|
||||
hash.isNotEmpty() && build.generation == 2 -> metadata("$CDN/v2/meta/${cdnPath(hash)}", null)
|
||||
hash.isNotEmpty() -> {
|
||||
val timestamp = manifest.getJSONObject("product").getString("timestamp")
|
||||
metadata("$CDN/v1/manifests/$product/windows/$timestamp/$hash", token)
|
||||
}
|
||||
depot.has("files") -> JSONObject().put("depot", depot)
|
||||
else -> error("GOG depot manifest is missing")
|
||||
}
|
||||
val entries = content.getJSONObject("depot").optJSONArray(if (build.generation == 2) "items" else "files") ?: error("GOG depot files are missing")
|
||||
for (entry in entries.objects()) {
|
||||
val type = entry.optString("type")
|
||||
check(type != "DepotLink") { "This GOG build contains unsupported file links" }
|
||||
val support = depot.optBoolean("support") || entry.optBoolean("support") || entry.optJSONArray("flags")?.strings()?.contains("support") == true
|
||||
val relative = entry.getString("path").replace('\\', '/').trimEnd('/').let { if (build.generation == 1) it.trimStart('/') else it }
|
||||
val path = if (support) (if (build.generation == 1) "support/$relative" else "support/$product/$relative") else relative
|
||||
val directory = type == "DepotDirectory" || entry.has("directory")
|
||||
val chunks = entry.optJSONArray("chunks") ?: JSONArray()
|
||||
val size = if (build.generation == 2) chunks.objects().sumOf { it.optLong("size") } else entry.optLong("size")
|
||||
files.put(JSONObject().put("path", path).put("size", size).put("directory", directory)
|
||||
.put("md5", entry.optString("md5").ifBlank { entry.optString("hash") }.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) }.orEmpty())
|
||||
.put("sha256", entry.optString("sha256")).put("chunks", chunks).put("product", product)
|
||||
.put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?')))
|
||||
}
|
||||
}
|
||||
check(files.length() > 0) { "GOG build contains no matching files" }
|
||||
return old.copy(source = "depot", generation = build.generation, build = build.id, version = build.version,
|
||||
branch = build.branch, language = resolvedLanguage, manifest = sanitize(manifest), files = files, products = products, verified = true)
|
||||
}
|
||||
|
||||
fun languageSelected(list: List<String>, selected: String): Boolean = list.any { it.equals("Neutral", true) } || StoreLanguage.depotMatchesResolved(list.toTypedArray(), selected)
|
||||
|
||||
fun cdnPath(hash: String): String {
|
||||
require(hash.matches(Regex("[a-fA-F0-9]{32,64}"))) { "Invalid GOG content hash" }
|
||||
return "${hash.take(2)}/${hash.substring(2, 4)}/$hash"
|
||||
}
|
||||
|
||||
fun links(record: GogInstallRecord, token: String, patches: Boolean = false): JSONObject {
|
||||
val out = JSONObject()
|
||||
for (id in record.products) {
|
||||
val path = if (record.generation == 1) "/windows/${record.manifest.optJSONObject("product")?.optString("timestamp")}/" else "/"
|
||||
val query = "_version=2&" + (if (record.generation == 1) "type=depot" else "generation=2") + "&path=${java.net.URLEncoder.encode(path, "UTF-8")}" + if (patches) "&root=%2Fpatches%2Fstore" else ""
|
||||
val response = json("$SYSTEM/products/$id/secure_link?$query", token)
|
||||
val bases = response.optJSONArray("urls")?.objects().orEmpty().mapNotNull { item ->
|
||||
val params = item.optJSONObject("parameters")
|
||||
var url = item.optString("url_format")
|
||||
params?.keys()?.forEach { key -> url = url.replace("{$key}", params.getString(key)) }
|
||||
url.takeIf { it.startsWith("https://") }
|
||||
}
|
||||
check(bases.isNotEmpty()) { "GOG refused a download link" }
|
||||
out.put(id, JSONArray(bases))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun patches(old: GogInstallRecord, target: GogInstallRecord, token: String): JSONArray {
|
||||
if (old.generation != 2 || target.generation != 2 || old.build.isBlank() || old.build == target.build) return JSONArray()
|
||||
return runCatching {
|
||||
val index = json("$SYSTEM/products/${old.id}/patches?_version=4&from_build_id=${old.build}&to_build_id=${target.build}", token)
|
||||
val meta = json(index.getString("link"), token)
|
||||
if (meta.optString("algorithm") != "xdelta3") return@runCatching JSONArray()
|
||||
val result = JSONArray()
|
||||
for (depot in meta.getJSONArray("depots").objects()) {
|
||||
if (depot.optString("productId") !in target.products || !languageSelected(depot.optJSONArray("languages")?.strings().orEmpty(), target.language)) continue
|
||||
val data = json("$CDN/v2/patches/meta/${cdnPath(depot.getString("manifest"))}")
|
||||
for (item in data.getJSONObject("depot").getJSONArray("items").objects()) if (item.optString("type") == "DepotDiff")
|
||||
result.put(JSONObject(item.toString()).put("product", depot.getString("productId")))
|
||||
}
|
||||
result
|
||||
}.getOrElse { JSONArray() }
|
||||
}
|
||||
|
||||
fun setupFiles(record: GogInstallRecord, token: String): Pair<JSONArray, JSONObject>? {
|
||||
if (!record.manifest.optBoolean("scriptInterpreter")) return null
|
||||
if (record.files.objects().none { file -> record.products.any { file.optString("path").substringAfterLast('/') == "goggame-$it.script" } }) return null
|
||||
val index = json("$SYSTEM/dependencies/repository?generation=2")
|
||||
val repository = json(index.getString("repository_manifest"))
|
||||
val depot = repository.getJSONArray("depots").objects().firstOrNull { it.optString("dependencyId") == "ISI" }
|
||||
?: error("GOG setup interpreter is unavailable")
|
||||
val content = json("$CDN/v2/dependencies/meta/${cdnPath(depot.getString("manifest"))}")
|
||||
val files = JSONArray()
|
||||
for (entry in content.getJSONObject("depot").getJSONArray("items").objects()) {
|
||||
if (entry.optString("type") != "DepotFile") continue
|
||||
val chunks = entry.getJSONArray("chunks")
|
||||
files.put(JSONObject().put("path", "support/" + entry.getString("path").replace('\\', '/'))
|
||||
.put("size", chunks.objects().sumOf { it.getLong("size") }).put("md5", entry.optString("md5"))
|
||||
.put("chunks", chunks).put("product", "redist"))
|
||||
}
|
||||
val response = json("$SYSTEM/open_link?generation=2&_version=2&path=%2Fdependencies%2Fstore%2F", token)
|
||||
val bases = GogDownloadManager.parseCdnUrls(response.toString())
|
||||
check(bases.isNotEmpty()) { "GOG setup download links are unavailable" }
|
||||
return files to JSONObject().put("redist", JSONArray(bases))
|
||||
}
|
||||
|
||||
fun sanitize(value: JSONObject): JSONObject {
|
||||
val result = JSONObject()
|
||||
for (key in value.keys()) {
|
||||
if (key.lowercase() in setOf("clientsecret", "access_token", "refresh_token", "link", "urls", "url")) continue
|
||||
val v = value.get(key)
|
||||
result.put(key, when (v) { is JSONObject -> sanitize(v); is JSONArray -> JSONArray((0 until v.length()).map { i -> v.get(i).let { if (it is JSONObject) sanitize(it) else it } }); else -> v })
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -106,7 +106,7 @@ public final class GogDownloadManager {
|
||||
String builds1Json = httpGet(builds1Url, null);
|
||||
if (builds1Json == null) builds1Json = httpGet(builds1Url, token);
|
||||
if (builds1Json == null) throw new InstallException("No builds available for this game");
|
||||
Gen1Outcome one = runGen1(ctx, game, token, builds1Json, installPath, cb, cancelled);
|
||||
Gen1Outcome one = runGen1(ctx, game, token, builds1Json, installPath, cb, cancelled, lang);
|
||||
if (one.result != null || cancelled.get()) return one.result;
|
||||
if (!"NO_CS_BUILDS".equals(one.error)) throw new InstallException("Download failed: " + one.error);
|
||||
cb.onProgress("No Galaxy builds; fetching the installer…", 12);
|
||||
@@ -250,6 +250,11 @@ public final class GogDownloadManager {
|
||||
if (anyFailed.get()) { out.error = "one or more chunks failed to download"; return out; }
|
||||
|
||||
cb.onProgress("Finishing…", 96);
|
||||
try {
|
||||
GogMaintenance.captureDepot(game.gameId, installPath, gm.buildId, buildsJson, manifest, new JSONArray(depotJsons), resolved);
|
||||
} catch (Exception e) {
|
||||
cb.onLog("gog: maintenance inventory not recorded: " + e.getMessage());
|
||||
}
|
||||
writeFile(new File(installPath, MARKER), ("{\"gameId\":\"" + game.gameId + "\",\"buildId\":\"" + gm.buildId + "\"}").getBytes("UTF-8"));
|
||||
deleteCounted(new File(installPath, ".gog_chunks"), cb);
|
||||
String clientId = manifest.optString("clientId", null);
|
||||
@@ -279,7 +284,7 @@ public final class GogDownloadManager {
|
||||
String buildId = null, manifestUrl = null;
|
||||
for (int i = 0; i < items.length(); i++) {
|
||||
JSONObject item = items.getJSONObject(i);
|
||||
if ("windows".equals(item.optString("os"))) {
|
||||
if ("windows".equals(item.optString("os")) && (item.isNull("branch") || item.optString("branch").isEmpty())) {
|
||||
buildId = item.optString("build_id");
|
||||
manifestUrl = item.optString("link");
|
||||
if (manifestUrl == null || manifestUrl.isEmpty()) manifestUrl = item.optString("meta_url");
|
||||
@@ -328,7 +333,7 @@ public final class GogDownloadManager {
|
||||
|
||||
private static final class Gen1Outcome { Result result; String error; }
|
||||
|
||||
private static Gen1Outcome runGen1(Context ctx, GogGame game, String token, String buildsJson, File installPath, Callback cb, AtomicBoolean cancelled) {
|
||||
private static Gen1Outcome runGen1(Context ctx, GogGame game, String token, String buildsJson, File installPath, Callback cb, AtomicBoolean cancelled, String language) {
|
||||
Gen1Outcome out = new Gen1Outcome();
|
||||
try {
|
||||
JSONObject builds = new JSONObject(buildsJson);
|
||||
@@ -346,6 +351,15 @@ public final class GogDownloadManager {
|
||||
String manifestStr = decompressBytes(raw);
|
||||
if (manifestStr == null) { out.error = "manifest decompress failed"; return out; }
|
||||
JSONObject manifest = new JSONObject(manifestStr);
|
||||
if (manifest.has("product")) {
|
||||
try {
|
||||
out.result = GogMaintenance.installContent(ctx, game, installPath, builds, language, cb, cancelled);
|
||||
if (out.result == null && !cancelled.get()) out.error = "no usable public Windows build";
|
||||
} catch (Exception e) {
|
||||
out.error = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
JSONArray depots = manifest.optJSONArray("depot");
|
||||
if (depots == null) { out.error = "no depot array"; return out; }
|
||||
List<Gen1File> files = new ArrayList<>();
|
||||
@@ -472,6 +486,7 @@ public final class GogDownloadManager {
|
||||
String exe = pickExe(installPath, null, game.title);
|
||||
if (exe.isEmpty()) throw new InstallException("The installer was extracted but no game executable was found");
|
||||
cb.onLog("gog: installer extracted natively; game exe " + exe);
|
||||
GogMaintenance.captureOffline(game.gameId, installPath, downloads);
|
||||
return new Result(exe, "", total);
|
||||
} catch (InstallerException e) {
|
||||
throw e;
|
||||
@@ -576,13 +591,13 @@ public final class GogDownloadManager {
|
||||
return cleaned.isEmpty() ? "game" : cleaned;
|
||||
}
|
||||
|
||||
private static String resolveRedirect(String url, String token) {
|
||||
static String resolveRedirect(String url, String token) {
|
||||
try {
|
||||
if (url.startsWith("/")) url = "https://www.gog.com" + url;
|
||||
for (int hop = 0; hop < 5; hop++) {
|
||||
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
|
||||
conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setInstanceFollowRedirects(false);
|
||||
if (token != null) conn.setRequestProperty("Authorization", "Bearer " + token);
|
||||
if (token != null && (new URL(url).getHost().equals("gog.com") || new URL(url).getHost().endsWith(".gog.com"))) conn.setRequestProperty("Authorization", "Bearer " + token);
|
||||
int code = conn.getResponseCode();
|
||||
String location = conn.getHeaderField("Location");
|
||||
if (code == 301 || code == 302 || code == 303 || code == 307 || code == 308) {
|
||||
@@ -686,6 +701,7 @@ public final class GogDownloadManager {
|
||||
cb.onBytes(shown, planned, speedBps.get());
|
||||
}
|
||||
@Override public void onLog(String line) { cb.onLog(line); }
|
||||
@Override public void onMaintenance(long networkBytes, long reusedBytes, long appliedBytes) {}
|
||||
@Override public void onComplete(boolean success, boolean wasCancelled, boolean linkExpiry, String error, long bytesWritten, int filesDone) {
|
||||
okRef.set(success); linkExpiryRef.set(linkExpiry); errRef.set(error == null ? "" : error); latch.countDown();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.security.MessageDigest
|
||||
|
||||
internal object GogEstimate {
|
||||
data class Size(val download: Long, val required: Long)
|
||||
private data class Chunk(val file: File, val offset: Long)
|
||||
|
||||
fun range(file: File, offset: Long, size: Long, md5: String): Boolean {
|
||||
if (!file.isFile || offset < 0 || size < 0 || file.length() < offset + size || !md5.matches(Regex("[a-fA-F0-9]{32}"))) return false
|
||||
return runCatching {
|
||||
RandomAccessFile(file, "r").use { input ->
|
||||
input.seek(offset)
|
||||
val digest = MessageDigest.getInstance("MD5"); val buffer = ByteArray(64 * 1024); var left = size
|
||||
while (left > 0) { val n = input.read(buffer, 0, minOf(left, buffer.size.toLong()).toInt()); check(n > 0); digest.update(buffer, 0, n); left -= n }
|
||||
digest.digest().joinToString("") { "%02x".format(it) }.equals(md5, true)
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
fun calculate(folder: File, old: GogInstallRecord, target: GogInstallRecord, patches: JSONArray, reuseChunks: Boolean = true): Size {
|
||||
val reusable = HashMap<Pair<String, Long>, MutableList<Chunk>>()
|
||||
for (file in old.files.objects()) {
|
||||
val source = GogFiles.inside(folder, file.getString("path")); var offset = 0L
|
||||
for (chunk in file.optJSONArray("chunks")?.objects().orEmpty()) {
|
||||
reusable.getOrPut(chunk.optString("md5").lowercase() to chunk.optLong("size")) { ArrayList() }.add(Chunk(source, offset))
|
||||
offset += chunk.optLong("size")
|
||||
}
|
||||
}
|
||||
var download = 0L; var required = 0L
|
||||
for (file in target.files.objects()) {
|
||||
if (file.optBoolean("directory") || GogFiles.matches(folder, file)) continue
|
||||
val chunks = file.optJSONArray("chunks")?.objects().orEmpty()
|
||||
val stamp = MessageDigest.getInstance("MD5").digest(file.getString("path").toByteArray()).joinToString("") { "%02x".format(it) }
|
||||
val stage = File(GogFiles.dir(folder), "stage/$stamp")
|
||||
var offset = 0L
|
||||
var cost = if (chunks.isEmpty()) file.getLong("size") else chunks.sumOf { chunk ->
|
||||
val size = chunk.getLong("size"); val hash = chunk.getString("md5")
|
||||
val exists = reuseChunks && (range(stage, offset, size, hash) || reusable[hash.lowercase() to size].orEmpty().any { range(it.file, it.offset, size, hash) })
|
||||
offset += size
|
||||
if (exists) 0L else chunk.optLong("compressedSize")
|
||||
}
|
||||
val patch = patches.objects().firstOrNull { it.optString("path_target").replace('\\', '/') == file.getString("path") }
|
||||
if (reuseChunks && patch != null) {
|
||||
val source = GogFiles.inside(folder, patch.getString("path_source").replace('\\', '/'))
|
||||
val delta = patch.getJSONArray("chunks").objects().sumOf { it.optLong("compressedSize") }
|
||||
if (delta < cost && source.isFile && GogFiles.hash(source).equals(patch.getString("md5_source"), true)) cost = delta
|
||||
}
|
||||
download = Math.addExact(download, cost)
|
||||
required = Math.addExact(required, maxOf(0, file.getLong("size") - stage.length()) + cost)
|
||||
}
|
||||
return Size(download, required)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.zip.InflaterInputStream
|
||||
|
||||
internal object GogFallback {
|
||||
fun transfer(folder: File, plan: JSONObject, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean,
|
||||
callback: GogDownloadManager.Callback? = null) {
|
||||
val stageRoot = File(GogFiles.dir(folder), "stage").apply { mkdirs() }
|
||||
val files = plan.getJSONArray("files")
|
||||
GogFiles.validate(files, folder)
|
||||
var wire = 0L
|
||||
fun progress(n: Int) { wire += n; handle?.progress(wire, plan.optLong("downloadBytes").coerceAtLeast(wire)); callback?.onBytes(wire, plan.optLong("downloadBytes").coerceAtLeast(wire), 0) }
|
||||
for ((index, item) in files.objects().withIndex()) {
|
||||
if (stop.get()) return
|
||||
val destination = GogFiles.inside(folder, item.getString("path"))
|
||||
if (item.optBoolean("directory")) { java.nio.file.Files.createDirectories(destination.toPath()); continue }
|
||||
if (GogFiles.matches(folder, item)) continue
|
||||
val stage = File(stageRoot, java.security.MessageDigest.getInstance("MD5").digest(item.getString("path").toByteArray()).joinToString("") { "%02x".format(it) })
|
||||
val chunks = item.optJSONArray("chunks")?.objects().orEmpty()
|
||||
FileOutputStream(stage).use { output ->
|
||||
if (chunks.isNotEmpty()) {
|
||||
for (chunk in chunks) {
|
||||
if (stop.get()) return
|
||||
val packed = File(stageRoot, "${stage.name}.packed")
|
||||
val urls = endpoints(plan.getJSONObject("links"), item.getString("product"), GogContent.cdnPath(chunk.getString("compressedMd5")))
|
||||
download(urls, packed, chunk.getLong("compressedSize"), stop, ::progress)
|
||||
check(GogFiles.hash(packed).equals(chunk.getString("compressedMd5"), true)) { "GOG compressed chunk checksum mismatch" }
|
||||
val digest = java.security.MessageDigest.getInstance("MD5")
|
||||
var count = 0L
|
||||
packed.inputStream().buffered().use { raw ->
|
||||
raw.mark(2); val first = raw.read(); raw.reset()
|
||||
val stored = chunk.getLong("size") == chunk.getLong("compressedSize") && chunk.getString("md5").equals(chunk.getString("compressedMd5"), true)
|
||||
val input = if (!stored && first == 0x78) InflaterInputStream(raw) else raw
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
if (stop.get()) return
|
||||
val n = input.read(buffer); if (n < 0) break
|
||||
count += n; check(count <= chunk.getLong("size")) { "GOG chunk exceeds expected size" }
|
||||
digest.update(buffer, 0, n); output.write(buffer, 0, n)
|
||||
}
|
||||
}
|
||||
check(count == chunk.getLong("size") && digest.digest().joinToString("") { "%02x".format(it) }.equals(chunk.getString("md5"), true)) { "GOG chunk checksum mismatch" }
|
||||
packed.delete()
|
||||
}
|
||||
} else if (item.getLong("size") > 0) {
|
||||
val remote = item.getString("remotePath")
|
||||
val urls = if (remote.startsWith("https://")) listOf(remote) else endpoints(plan.getJSONObject("links"), item.getString("product"), remote.trimStart('/'))
|
||||
val range = item.getLong("offset")
|
||||
val raw = File(stageRoot, "${stage.name}.range")
|
||||
download(urls, raw, item.getLong("size"), stop, ::progress, range)
|
||||
raw.inputStream().use { it.copyTo(output) }; raw.delete()
|
||||
}
|
||||
output.fd.sync()
|
||||
}
|
||||
if (stop.get()) return
|
||||
check(stage.length() == item.getLong("size")) { "GOG file size mismatch" }
|
||||
if (item.optString("md5").isNotBlank()) check(GogFiles.hash(stage).equals(item.getString("md5"), true)) { "GOG file checksum mismatch" }
|
||||
if (item.optString("sha256").isNotBlank()) check(GogFiles.hash(stage, "SHA-256").equals(item.getString("sha256"), true)) { "GOG file checksum mismatch" }
|
||||
destination.parentFile!!.mkdirs()
|
||||
GogFiles.inside(folder, item.getString("path"))
|
||||
GogFiles.replace(stage, destination)
|
||||
handle?.stage(DownloadStage.INSTALL); handle?.stageProgress((index + 1).toLong(), files.length().toLong())
|
||||
callback?.onProgress("Downloading: ${destination.name}", ((index + 1) * 100 / files.length()))
|
||||
}
|
||||
val targetPaths = files.objects().mapTo(HashSet()) { it.getString("path").lowercase(java.util.Locale.ROOT) }
|
||||
for (old in plan.optJSONArray("oldFiles")?.objects().orEmpty()) {
|
||||
if (stop.get()) return
|
||||
if (old.getString("path").lowercase(java.util.Locale.ROOT) !in targetPaths && GogFiles.matches(folder, old))
|
||||
check(GogFiles.inside(folder, old.getString("path")).delete()) { "Could not remove obsolete GOG file" }
|
||||
}
|
||||
}
|
||||
|
||||
fun endpoints(links: JSONObject, product: String, path: String): List<String> = links.getJSONArray(product).strings().map { base ->
|
||||
if (base.contains("{GALAXY_PATH}")) base.replace("{GALAXY_PATH}", path)
|
||||
else base.substringBefore('?').trimEnd('/') + "/" + path + if ('?' in base) "?" + base.substringAfter('?') else ""
|
||||
}
|
||||
|
||||
fun download(urls: List<String>, destination: File, size: Long, stop: AtomicBoolean, progress: (Int) -> Unit, range: Long? = null) {
|
||||
var failure: Throwable? = null
|
||||
for (attempt in 0..2) for (url in urls) {
|
||||
if (stop.get()) return
|
||||
val connection = URL(url).openConnection() as HttpURLConnection
|
||||
try {
|
||||
check(URL(url).protocol == "https" || URL(url).host in setOf("127.0.0.1", "localhost"))
|
||||
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
|
||||
if (range != null) connection.setRequestProperty("Range", "bytes=$range-${range + size - 1}")
|
||||
check(connection.responseCode == if (range == null) 200 else 206) { "GOG download failed (HTTP ${connection.responseCode})" }
|
||||
FileOutputStream(destination).use { output ->
|
||||
connection.inputStream.use { input ->
|
||||
val buffer = ByteArray(64 * 1024); var count = 0L
|
||||
while (true) {
|
||||
if (stop.get()) return
|
||||
val n = input.read(buffer); if (n < 0) break
|
||||
count += n; check(size <= 0 || count <= size) { "GOG response exceeds expected size" }
|
||||
output.write(buffer, 0, n); progress(n)
|
||||
}
|
||||
check(size <= 0 || count == size) { "Incomplete GOG download" }
|
||||
}
|
||||
output.fd.sync()
|
||||
}
|
||||
return
|
||||
} catch (e: Exception) { failure = e }
|
||||
finally { connection.disconnect() }
|
||||
}
|
||||
throw failure ?: IllegalStateException("No GOG download URL")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.nio.file.StandardCopyOption
|
||||
import java.security.MessageDigest
|
||||
import java.util.Locale
|
||||
|
||||
internal enum class GogOperation { UPDATE, REPAIR, PATCH, REFRESH }
|
||||
|
||||
internal data class GogInstallRecord(
|
||||
val id: String,
|
||||
val source: String,
|
||||
val generation: Int = 0,
|
||||
val build: String = "",
|
||||
val version: String = "",
|
||||
val branch: String = "",
|
||||
val language: String = "en-US",
|
||||
val products: List<String> = listOf(id),
|
||||
val manifest: JSONObject = JSONObject(),
|
||||
val files: JSONArray = JSONArray(),
|
||||
val verified: Boolean = true,
|
||||
) {
|
||||
fun json() = JSONObject().put("schema", 1).put("id", id).put("source", source)
|
||||
.put("generation", generation).put("build", build).put("version", version).put("branch", branch)
|
||||
.put("language", language).put("products", JSONArray(products)).put("manifest", manifest)
|
||||
.put("files", files).put("verified", verified)
|
||||
|
||||
fun write(folder: File) = GogFiles.write(File(GogFiles.dir(folder), "installed.json"), json())
|
||||
|
||||
companion object {
|
||||
fun parse(o: JSONObject): GogInstallRecord {
|
||||
require(o.optInt("schema") == 1) { "Unsupported GOG installation record" }
|
||||
return GogInstallRecord(o.getString("id"), o.getString("source"), o.optInt("generation"),
|
||||
o.optString("build"), o.optString("version"), o.optString("branch"), o.optString("language", "en-US"),
|
||||
o.optJSONArray("products")?.strings().orEmpty().ifEmpty { listOf(o.getString("id")) },
|
||||
o.optJSONObject("manifest") ?: JSONObject(), o.optJSONArray("files") ?: JSONArray(), o.optBoolean("verified", true))
|
||||
}
|
||||
|
||||
fun read(folder: File): GogInstallRecord? = GogFiles.read(File(GogFiles.dir(folder), "installed.json"))?.let(::parse)
|
||||
|
||||
fun authenticBuild(folder: File, id: String): String = GogFiles.read(File(folder, "goggame-$id.id"))?.optString("buildId").orEmpty()
|
||||
.ifBlank { GogFiles.read(File(folder, "goggame-$id.info"))?.optString("buildId").orEmpty() }
|
||||
|
||||
fun migrate(folder: File, sidecar: StoreGameSidecar): GogInstallRecord {
|
||||
read(folder)?.let { require(it.id == sidecar.id); return it }
|
||||
val legacy = GogFiles.read(File(folder, "_gog_manifest.json"))
|
||||
val info = GogFiles.read(File(folder, "goggame-${sidecar.id}.info"))
|
||||
val build = authenticBuild(folder, sidecar.id).ifBlank { legacy?.optString("buildId").orEmpty().ifBlank { sidecar.installVersion } }
|
||||
val ids = folder.listFiles().orEmpty().mapNotNull { Regex("goggame-([0-9]+)\\.info").matchEntire(it.name)?.groupValues?.get(1) }
|
||||
return GogInstallRecord(sidecar.id, if (legacy != null || sidecar.installVersion.isNotBlank()) "depot" else "offline",
|
||||
legacy?.optInt("generation", if (build.isNotBlank()) 2 else 0) ?: if (build.isNotBlank()) 2 else 0,
|
||||
build, info?.optString("versionName").orEmpty(), language = sidecar.extra[com.droiddeck.launcher.stores.StoreLanguage.EXTRA] ?: "en-US",
|
||||
products = (listOf(sidecar.id) + ids).distinct()).also { it.write(folder) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal object GogFiles {
|
||||
fun dir(folder: File): File = inside(folder, ".droiddeck-gog").apply { mkdirs() }
|
||||
fun journal(folder: File): File = File(dir(folder), "operation.json")
|
||||
|
||||
fun inside(root: File, raw: String): File {
|
||||
val path = raw.replace('\\', '/')
|
||||
require(path.isNotBlank() && !path.startsWith('/') && ':' !in path && '\u0000' !in path &&
|
||||
path.split('/').none { it.isEmpty() || it == "." || it == ".." }) { "Invalid GOG path: $raw" }
|
||||
val base = root.canonicalFile
|
||||
var out = base
|
||||
for (part in path.split('/')) {
|
||||
out = File(out, part)
|
||||
require(!Files.isSymbolicLink(out.toPath())) { "GOG path is a symbolic link: $raw" }
|
||||
}
|
||||
require(out.canonicalFile.toPath().startsWith(base.toPath())) { "GOG path leaves installation" }
|
||||
return out
|
||||
}
|
||||
|
||||
fun read(file: File): JSONObject? {
|
||||
require(!Files.isSymbolicLink(file.toPath())) { "GOG metadata is a symbolic link" }
|
||||
return if (!file.exists()) null else JSONObject(file.readText())
|
||||
}
|
||||
|
||||
fun write(file: File, value: JSONObject) {
|
||||
require(!Files.isSymbolicLink(file.toPath()))
|
||||
file.parentFile!!.mkdirs()
|
||||
val tmp = File.createTempFile(".gog-", ".stage", file.parentFile)
|
||||
try {
|
||||
FileOutputStream(tmp).use { it.write(value.toString().toByteArray(Charsets.UTF_8)); it.fd.sync() }
|
||||
replace(tmp, file)
|
||||
} finally { tmp.delete() }
|
||||
}
|
||||
|
||||
fun replace(from: File, to: File) {
|
||||
require(!Files.isSymbolicLink(to.toPath()))
|
||||
try { Files.move(from.toPath(), to.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
|
||||
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING) }
|
||||
}
|
||||
|
||||
fun hash(file: File, algorithm: String = "MD5"): String {
|
||||
val digest = MessageDigest.getInstance(algorithm)
|
||||
file.inputStream().use { input -> val buffer = ByteArray(128 * 1024); while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) } }
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
fun matches(folder: File, file: JSONObject): Boolean {
|
||||
val f = inside(folder, file.getString("path"))
|
||||
if (!Files.isRegularFile(f.toPath(), LinkOption.NOFOLLOW_LINKS) || f.length() != file.getLong("size")) return false
|
||||
val md5 = file.optString("md5")
|
||||
if (md5.matches(Regex("[a-fA-F0-9]{32}"))) return hash(f).equals(md5, true)
|
||||
val sha = file.optString("sha256")
|
||||
if (sha.isNotBlank()) return hash(f, "SHA-256").equals(sha, true)
|
||||
val chunks = file.optJSONArray("chunks")?.objects().orEmpty()
|
||||
var offset = 0L
|
||||
return chunks.isNotEmpty() && chunks.all { chunk ->
|
||||
val result = GogEstimate.range(f, offset, chunk.getLong("size"), chunk.getString("md5"))
|
||||
offset += chunk.getLong("size"); result
|
||||
} || f.length() == 0L
|
||||
}
|
||||
|
||||
fun validate(files: JSONArray, folder: File) {
|
||||
val paths = HashSet<String>()
|
||||
val components = HashMap<String, String>()
|
||||
for (file in files.objects()) {
|
||||
val path = file.getString("path").replace('\\', '/')
|
||||
inside(folder, path)
|
||||
require(!path.startsWith(".droiddeck-", true) && path != StoreGameSidecar.FILE_NAME) { "GOG content overlaps launcher metadata" }
|
||||
require(paths.add(path.lowercase(Locale.ROOT))) { "GOG paths differ only by case: $path" }
|
||||
var parent = folder
|
||||
var relative = ""
|
||||
for (part in path.split('/')) {
|
||||
relative = if (relative.isEmpty()) part else "$relative/$part"
|
||||
val previous = components.putIfAbsent(relative.lowercase(Locale.ROOT), relative)
|
||||
require(previous == null || previous == relative) { "GOG directory paths differ only by case: $path" }
|
||||
require(parent.list()?.none { it != part && it.equals(part, true) } != false) { "An existing path differs only by case: $path" }
|
||||
parent = File(parent, part)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun JSONArray.objects(): List<JSONObject> = (0 until length()).map { getJSONObject(it) }
|
||||
internal fun JSONArray.strings(): List<String> = (0 until length()).map { optString(it) }
|
||||
|
||||
internal data class GogBuild(val id: String, val version: String, val generation: Int, val branch: String, val link: String) {
|
||||
companion object {
|
||||
fun select(builds: JSONObject, pinned: String = "", branch: String = ""): GogBuild? {
|
||||
val items = builds.optJSONArray("items")?.objects().orEmpty().filter { it.optString("os", "windows") == "windows" }
|
||||
val item = if (pinned.isNotBlank()) items.firstOrNull { it.optString("build_id") == pinned || it.optString("legacy_build_id") == pinned }
|
||||
else items.firstOrNull { it.optString("branch").let { b -> (if (b == "null") "" else b) == branch } }
|
||||
return item?.let { GogBuild(it.optString("build_id"), it.optString("version_name"), it.optInt("generation", 2),
|
||||
it.optString("branch").let { b -> if (b == "null") "" else b },
|
||||
it.optString("link").ifBlank { it.optString("meta_url").ifBlank { it.optJSONArray("urls")?.optJSONObject(0)?.optString("url").orEmpty() } }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal data class GogOfflinePart(val id: String, val name: String, val url: String, val size: Long, val md5: String)
|
||||
internal data class GogOfflineDownload(val id: String, val name: String, val version: String, val language: String, val parts: List<GogOfflinePart>) {
|
||||
val size: Long get() = parts.sumOf { it.size }
|
||||
companion object {
|
||||
fun parse(downloads: JSONObject, kind: String): List<GogOfflineDownload> = downloads.optJSONArray(kind)?.objects().orEmpty()
|
||||
.filter { it.optString("os") == "windows" }.mapNotNull { entry ->
|
||||
val files = entry.optJSONArray("files")?.objects().orEmpty()
|
||||
val parts = files.mapNotNull { f ->
|
||||
val url = f.optString("downlink").ifBlank { f.optString("manualUrl") }
|
||||
if (url.isBlank()) null else GogOfflinePart(f.optString("id"), f.optString("filename"), url, f.optLong("size"), f.optString("md5"))
|
||||
}
|
||||
if (parts.isEmpty()) null else GogOfflineDownload(entry.optString("id").ifBlank { parts.first().id },
|
||||
entry.optString("name", "GOG download"), entry.optString("version"), entry.optString("language"), parts)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import com.droiddeck.launcher.agent.AgentGuest
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.*
|
||||
import com.droiddeck.launcher.stores.download.*
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal object GogMaintenance {
|
||||
enum class State { UNKNOWN, CHECKING, CURRENT, AVAILABLE, FAILED }
|
||||
data class Check(val state: State, val version: String = "", val reason: String = "")
|
||||
data class Proposal(val folder: File, val before: GogInstallRecord, val target: GogInstallRecord,
|
||||
val operation: GogOperation, val downloadBytes: Long, val diskBytes: Long, val patch: GogOfflineDownload? = null, val deltas: JSONArray = JSONArray(), val fullFiles: Boolean = false)
|
||||
|
||||
val checks = mutableStateMapOf<String, Check>()
|
||||
private val workers = Executors.newFixedThreadPool(2)
|
||||
private val checkedAt = java.util.concurrent.ConcurrentHashMap<String, Long>()
|
||||
private val inFlight = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
|
||||
@Volatile private var account = ""
|
||||
private val revision = java.util.concurrent.atomic.AtomicLong()
|
||||
private const val HELPER = "/usr/local/bin/droiddeck-gog-maintenance"
|
||||
const val OPERATION = "gogOperation"
|
||||
const val FOLDER = "gogFolder"
|
||||
|
||||
fun reset() {
|
||||
revision.incrementAndGet()
|
||||
account = ""; checkedAt.clear()
|
||||
StoresState.post { checks.clear() }
|
||||
}
|
||||
|
||||
fun checkInstalled(context: Context, games: List<InstalledStoreGame>) {
|
||||
val user = StoreAccounts.displayName(context, Store.GOG).orEmpty()
|
||||
if (user != account) { reset(); account = user }
|
||||
if (user.isBlank()) return
|
||||
games.filter { it.sidecar.store == Store.GOG && it.sidecar.isInstalled }.forEach { check(context, it) }
|
||||
}
|
||||
|
||||
fun check(context: Context, game: InstalledStoreGame, force: Boolean = false) {
|
||||
val key = game.folder.absolutePath
|
||||
if (!force && System.currentTimeMillis() - (checkedAt[key] ?: 0) < 30 * 60_000) return
|
||||
if (!inFlight.add(key)) return
|
||||
val owner = revision.get()
|
||||
StoresState.post { checks[game.sidecar.id] = Check(State.CHECKING) }
|
||||
workers.execute {
|
||||
val result = runCatching {
|
||||
var old = GogInstallRecord.migrate(game.folder, game.sidecar)
|
||||
if (!old.verified || GogFiles.journal(game.folder).exists()) Check(State.UNKNOWN, reason = "Finish or recover the GOG maintenance operation first")
|
||||
else {
|
||||
val token = GogContent.token(context)
|
||||
if (old.source == "depot") {
|
||||
val builds = GogContent.builds(old.id, token)
|
||||
if (old.files.length() == 0 && old.build.isNotBlank()) GogBuild.select(builds, pinned = old.build)?.let { old = old.copy(branch = it.branch, generation = it.generation) }
|
||||
val latest = GogBuild.select(builds, branch = old.branch)
|
||||
when { latest == null -> Check(State.UNKNOWN, reason = "No build is available on the installed branch")
|
||||
old.build.isBlank() -> Check(State.UNKNOWN, latest.version, "The installed build is unknown")
|
||||
latest.id == old.build -> Check(State.CURRENT, old.version)
|
||||
else -> Check(State.AVAILABLE, latest.version) }
|
||||
} else {
|
||||
val downloads = GogContent.product(old.id, token).getJSONObject("downloads")
|
||||
val installer = offlineInstaller(downloads, old.language)
|
||||
if (old.version.isBlank()) Check(State.UNKNOWN, installer.version, "The installed version is unknown")
|
||||
else Check(if (old.version == installer.version) State.CURRENT else State.AVAILABLE, installer.version)
|
||||
}
|
||||
}
|
||||
}.getOrElse { Check(State.FAILED, reason = it.message ?: "GOG update check failed") }
|
||||
if (revision.get() == owner && (result.state == State.CURRENT || result.state == State.AVAILABLE)) checkedAt[key] = System.currentTimeMillis()
|
||||
inFlight.remove(key)
|
||||
StoresState.post { if (revision.get() == owner) checks[game.sidecar.id] = result }
|
||||
}
|
||||
}
|
||||
|
||||
fun offlinePatches(context: Context, game: InstalledStoreGame): List<GogOfflineDownload> =
|
||||
GogOfflineDownload.parse(GogContent.product(game.sidecar.id, GogContent.token(context)).getJSONObject("downloads"), "patches")
|
||||
|
||||
internal fun offlineInstaller(downloads: JSONObject, language: String): GogOfflineDownload {
|
||||
val installers = GogOfflineDownload.parse(downloads, "installers")
|
||||
return installers.firstOrNull { it.language.equals(language, true) }
|
||||
?: installers.firstOrNull { !it.language.equals("Neutral", true) && StoreLanguage.depotAccepted(arrayOf(it.language), language) }
|
||||
?: installers.firstOrNull { it.language.equals("Neutral", true) }
|
||||
?: error("No Windows offline installer is available for the installed language ($language)")
|
||||
}
|
||||
|
||||
fun prepare(context: Context, game: InstalledStoreGame, operation: GogOperation, patch: GogOfflineDownload? = null, resume: Boolean = false): Proposal {
|
||||
val folder = game.folder.canonicalFile
|
||||
var old = GogInstallRecord.migrate(folder, game.sidecar)
|
||||
val journal = GogFiles.read(GogFiles.journal(folder))
|
||||
require(journal == null || journal.optString("folder") == folder.path) { "GOG recovery folder does not match" }
|
||||
if (journal != null && journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain") && operation != GogOperation.REFRESH) error("The patch was interrupted. Inspect the installer result or use a full offline refresh; it will not be rerun automatically.")
|
||||
require(journal == null || operation == GogOperation.REFRESH || journal.optString("operation") == operation.name) { "Resume the existing GOG operation or select a full offline refresh" }
|
||||
val token = GogContent.token(context)
|
||||
if (operation == GogOperation.PATCH) {
|
||||
if (old.source == "depot" && old.manifest.length() == 0 && old.build.isNotBlank()) {
|
||||
val exact = GogBuild.select(GogContent.builds(old.id, token), pinned = old.build)
|
||||
?: error("The installed GOG setup manifest is unavailable; use a full offline refresh")
|
||||
old = GogContent.snapshot(old, exact, token)
|
||||
}
|
||||
check(patch != null) { "Select a GOG patch" }
|
||||
if (resume) require(journal?.optString("downloadVersion") == patch.version) { "The selected patch changed; select it again in Offline patches" }
|
||||
val selected = GogContent.resolveDownload(patch, token)
|
||||
return Proposal(folder, old, old.copy(source = "offline", version = selected.version, verified = false), operation, selected.size,
|
||||
selected.size + folder.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.name != ".droiddeck-gog" }.filter { it.isFile }.sumOf { it.length() }, selected)
|
||||
}
|
||||
if (operation == GogOperation.REFRESH || old.source != "depot") {
|
||||
require(operation != GogOperation.REPAIR) { "This offline installation has no depot manifest. Use a full offline refresh to restore its files." }
|
||||
val download = GogContent.resolveDownload(offlineInstaller(GogContent.product(old.id, token).getJSONObject("downloads"), old.language), token)
|
||||
if (resume) require(journal?.optString("downloadId") == download.id && journal.optString("downloadVersion") == download.version) { "The previous offline installer is no longer available; select a new full offline refresh" }
|
||||
if (old.products.any { it != old.id }) {
|
||||
val pinned = journal?.optJSONObject("target")?.optString("build").orEmpty()
|
||||
val build = GogBuild.select(GogContent.builds(old.id, token), pinned = pinned, branch = old.branch)
|
||||
?: error("No depot build is available to preserve installed DLC during this refresh. Use Update instead.")
|
||||
val target = GogContent.snapshot(old, build, token)
|
||||
GogFiles.validate(target.files, folder)
|
||||
val native = GogNative.isAvailable()
|
||||
val remaining = GogEstimate.calculate(folder, old, target, JSONArray(), reuseChunks = native)
|
||||
return Proposal(folder, old, target, GogOperation.REFRESH, Math.addExact(download.size, remaining.download),
|
||||
Math.addExact(Math.multiplyExact(download.size, 3), remaining.required), download, fullFiles = !native)
|
||||
}
|
||||
val target = old.copy(source = "offline", build = "", generation = 0, version = download.version, manifest = JSONObject(), files = JSONArray(), verified = true)
|
||||
return Proposal(folder, old, target, GogOperation.REFRESH, download.size, download.size * 3, download)
|
||||
}
|
||||
require(old.verified || operation != GogOperation.REPAIR) { "The patched installation must be reconciled before repair" }
|
||||
val pinned = journal?.optJSONObject("target")?.let(GogInstallRecord::parse)
|
||||
val builds = GogContent.builds(old.id, token)
|
||||
if (old.files.length() == 0 && old.build.isNotBlank()) GogBuild.select(builds, pinned = old.build)?.let { old = old.copy(branch = it.branch, generation = it.generation) }
|
||||
val build = GogBuild.select(builds,
|
||||
pinned = pinned?.build ?: if (operation == GogOperation.REPAIR) old.build.ifBlank { error("The installed GOG build is unknown; update it first") } else "",
|
||||
branch = pinned?.branch ?: old.branch) ?: error("The requested GOG build is no longer available")
|
||||
val target = GogContent.snapshot(old, build, token)
|
||||
GogFiles.validate(target.files, folder)
|
||||
var before = journal?.optJSONObject("before")?.let(GogInstallRecord::parse) ?: old
|
||||
if (before.files.length() == 0 && before.build.isNotBlank()) {
|
||||
val historical = GogBuild.select(builds, pinned = before.build)
|
||||
if (historical != null) before = runCatching { GogContent.snapshot(before, historical, token) }.getOrDefault(before)
|
||||
}
|
||||
val deltas = GogContent.patches(before, target, token)
|
||||
val native = GogNative.isAvailable()
|
||||
val size = GogEstimate.calculate(folder, before, target, deltas, reuseChunks = native)
|
||||
return Proposal(folder, before, target, operation, size.download, size.required, deltas = deltas, fullFiles = !native)
|
||||
}
|
||||
|
||||
fun resume(context: Context, game: InstalledStoreGame): Proposal {
|
||||
val journal = GogFiles.read(GogFiles.journal(game.folder)) ?: error("GOG operation journal is missing")
|
||||
val operation = GogOperation.valueOf(journal.getString("operation"))
|
||||
val patch = if (operation == GogOperation.PATCH) offlinePatches(context, game)
|
||||
.firstOrNull { it.id == journal.optString("downloadId") } ?: error("The selected GOG patch is no longer available") else null
|
||||
return prepare(context, game, operation, patch, resume = true)
|
||||
}
|
||||
|
||||
fun recoverPatch(context: Context, game: InstalledStoreGame) {
|
||||
val folder = game.folder.canonicalFile
|
||||
check(!DownloadQueue.isActive(game.key)) { "Wait for the GOG operation to finish" }
|
||||
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG patch journal is missing")
|
||||
require(journal.optString("folder") == folder.path && journal.optString("operation") == GogOperation.PATCH.name)
|
||||
require(journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain"))
|
||||
RandomAccessFile(GogFiles.inside(folder, ".droiddeck-gog/lease"), "rw").use { lease ->
|
||||
val lock = runCatching { lease.channel.tryLock() }.getOrNull() ?: error("Close the patch installer before verifying its result")
|
||||
lock.use {
|
||||
ensureIdle(context, folder)
|
||||
val before = GogInstallRecord.parse(journal.getJSONObject("before"))
|
||||
val buildId = GogInstallRecord.authenticBuild(folder, before.id).ifBlank { before.build }
|
||||
check(buildId.isNotBlank()) { "The resulting build is unknown. Use a full offline refresh." }
|
||||
val token = GogContent.token(context)
|
||||
val build = GogBuild.select(GogContent.builds(before.id, token), pinned = buildId)
|
||||
?: error("The resulting build manifest is unavailable. Use a full offline refresh.")
|
||||
val target = GogContent.snapshot(before, build, token)
|
||||
GogFiles.validate(target.files, folder)
|
||||
check(target.files.objects().all { it.optBoolean("directory") || GogFiles.matches(folder, it) }) {
|
||||
"The files do not match the reported build. Use a full offline refresh to recover."
|
||||
}
|
||||
val sidecar = StoreGameSidecar.parse(journal.getJSONObject("sidecar").toString()) ?: error("The original GOG settings are missing")
|
||||
target.write(folder)
|
||||
StoreInstalls.complete(context, folder, sidecar.copy(installVersion = target.build, state = StoreGameSidecar.STATE_INSTALLED))
|
||||
check(GogFiles.journal(folder).delete()) { "Could not finish the GOG recovery record" }
|
||||
}
|
||||
}
|
||||
checkedAt.remove(folder.path)
|
||||
DownloadQueue.dismiss(game.key)
|
||||
StoresState.notifyLibraryChanged(context)
|
||||
StoresState.post { checks.remove(game.sidecar.id) }
|
||||
}
|
||||
|
||||
fun enqueue(context: Context, game: InstalledStoreGame, proposal: Proposal) {
|
||||
val app = context.applicationContext
|
||||
require(game.folder.canonicalFile == proposal.folder)
|
||||
check(!DownloadQueue.isActive("gog:${game.sidecar.id}")) { "GOG maintenance is already queued" }
|
||||
check(!StoreInstallRoot.insufficientSpace(proposal.diskBytes, StoreInstallRoot.availableBytes(proposal.folder))) { "Not enough free space for GOG maintenance" }
|
||||
val journal = JSONObject().put("schema", 1).put("folder", proposal.folder.path).put("operation", proposal.operation.name)
|
||||
.put("before", proposal.before.json()).put("target", proposal.target.json()).put("sidecar", game.sidecar.toJson()).put("phase", "download")
|
||||
proposal.patch?.let { journal.put("downloadId", it.id).put("downloadVersion", it.version) }
|
||||
GogFiles.write(GogFiles.journal(proposal.folder), journal)
|
||||
val item = CatalogItem(Store.GOG, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover,
|
||||
extra = mapOf(OPERATION to proposal.operation.name, FOLDER to proposal.folder.path))
|
||||
SavedQueue.remember(app, item, null)
|
||||
enqueueJob(app, item, proposal)
|
||||
}
|
||||
|
||||
private fun enqueueJob(context: Context, item: CatalogItem, proposal: Proposal) {
|
||||
DownloadQueue.enqueue(context, DownloadEntry(Store.GOG, item.id, item.title, cover = item.tallImageUrl,
|
||||
bytesTotal = proposal.downloadBytes, location = StoreInstallRoot.labelFor(context, proposal.folder))) { Job(context, proposal) }
|
||||
}
|
||||
|
||||
fun restore(context: Context, item: CatalogItem) {
|
||||
val folder = File(item.extra[FOLDER] ?: error("Missing GOG recovery folder")).canonicalFile
|
||||
require(StoreInstallRoot.gameFolders(context).any { it.canonicalFile == folder }) { "GOG recovery folder is unavailable" }
|
||||
val sidecar = StoreGameSidecar.read(folder) ?: error("GOG installation record is missing")
|
||||
require(sidecar.store == Store.GOG && sidecar.id == item.id)
|
||||
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG operation journal is missing")
|
||||
val operation = GogOperation.valueOf(journal.getString("operation"))
|
||||
if (journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain")) {
|
||||
DownloadQueue.recordFailed(context, DownloadEntry(Store.GOG, item.id, item.title), "The patch result needs recovery; open Offline patches")
|
||||
return
|
||||
}
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
SavedQueue.remember(context, item, null)
|
||||
enqueueJob(context, item, resume(context, game))
|
||||
}
|
||||
|
||||
private class Job(val app: Context, val proposal: Proposal) : DownloadQueue.DownloadJob {
|
||||
val cancelled = AtomicBoolean(false)
|
||||
@Volatile var applyingPatch = false
|
||||
@Volatile private var running = false
|
||||
@Volatile private var deleteCaches = false
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
if (applyingPatch) return
|
||||
deleteCaches = deleteCaches || deleteFiles
|
||||
cancelled.set(true)
|
||||
if (!running && deleteCaches) cleanCaches()
|
||||
}
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
running = true
|
||||
try { return perform(handle) }
|
||||
finally {
|
||||
running = false; applyingPatch = false; handle.interruptible(true)
|
||||
if (deleteCaches) cleanCaches()
|
||||
}
|
||||
}
|
||||
|
||||
private fun cleanCaches() {
|
||||
for (name in listOf("stage", "downloads", "extracted")) {
|
||||
val root = GogFiles.inside(proposal.folder, ".droiddeck-gog/$name")
|
||||
if (root.exists()) java.nio.file.Files.walk(root.toPath()).use { paths ->
|
||||
paths.sorted(java.util.Comparator.reverseOrder()).forEach { java.nio.file.Files.deleteIfExists(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun perform(handle: DownloadQueue.JobHandle): String? {
|
||||
val folder = proposal.folder
|
||||
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG operation journal is missing")
|
||||
val sidecar = StoreGameSidecar.parse(journal.getJSONObject("sidecar").toString()) ?: error("GOG previous installation is missing")
|
||||
if (proposal.operation == GogOperation.PATCH) {
|
||||
val result = GogOffline.apply(app, proposal, handle, cancelled, onApplying = { applyingPatch = true; handle.interruptible(false) })
|
||||
applyingPatch = false; handle.interruptible(true)
|
||||
if (!result || cancelled.get()) return null
|
||||
} else {
|
||||
RandomAccessFile(GogFiles.inside(folder, ".droiddeck-gog/lease"), "rw").use { lease ->
|
||||
val lock = runCatching { lease.channel.tryLock() }.getOrNull() ?: error("Close the GOG game before updating it")
|
||||
lock.use {
|
||||
ensureIdle(app, folder)
|
||||
sidecar.copy(state = StoreGameSidecar.STATE_UPDATING).write(folder)
|
||||
GogFiles.write(GogFiles.journal(folder), journal.put("phase", "applying"))
|
||||
if (proposal.operation == GogOperation.REFRESH) {
|
||||
GogOffline.refresh(app, proposal, handle, cancelled)
|
||||
if (!cancelled.get() && proposal.target.source == "depot") transfer(app, proposal, handle, cancelled)
|
||||
} else transfer(app, proposal, handle, cancelled)
|
||||
if (cancelled.get()) return null
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cancelled.get()) return null
|
||||
val target = GogInstallRecord.read(folder)?.takeIf { proposal.operation == GogOperation.PATCH || proposal.operation == GogOperation.REFRESH && proposal.target.source != "depot" } ?: proposal.target
|
||||
check(target.verified) { "The patch completed, but its resulting version could not be verified. Inspect the game or use a full offline refresh." }
|
||||
target.write(folder)
|
||||
StoreInstalls.complete(app, folder, sidecar.copy(installVersion = target.build.ifBlank { target.version }, state = StoreGameSidecar.STATE_INSTALLED))
|
||||
check(GogFiles.journal(folder).delete()) { "Could not finish the GOG recovery record" }
|
||||
runCatching { cleanCaches() }.onFailure { handle.log("gog: completed; could not remove expendable cache: ${it.message}") }
|
||||
checkedAt.remove(folder.path)
|
||||
StoresState.post { checks.remove(sidecar.id) }
|
||||
return folder.path
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureIdle(context: Context, folder: File) {
|
||||
val game = AddedGames.single(context, folder.path) ?: return
|
||||
check(SessionState.gameId != (game.appId and 0xffffffffL).toString()) { "Close the GOG game before maintenance" }
|
||||
if (SessionState.running) {
|
||||
val id = (game.steamAppId?.toLong() ?: game.appId) and 0xffffffffL
|
||||
val guest = AddedGames.guestPath(context, folder) ?: error("The GOG folder is unavailable to Linux")
|
||||
if (SessionState.suspended || AgentGuest.hello(context) == null) {
|
||||
val root = AddedGames.guestPath(context, SessionPrefs.activeSteamRoot(context)) ?: error("The Steam folder is unavailable to Linux")
|
||||
val rc = GuestCommand.run(context, listOf("/usr/bin/env", "STEAM_COMPAT_CLIENT_INSTALL_PATH=$root", HELPER, "idle", guest, id.toString(), game.guestExe),
|
||||
extraBinds = StoreInstallRoot.externalBindSpecs(context), logName = "gog-idle", onLine = StoresState::logLine)
|
||||
check(rc == 0) { "Close the GOG game before maintenance" }
|
||||
return
|
||||
}
|
||||
val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, "idle", guest, id.toString(), game.guestExe))).put("timeout", 15)
|
||||
val result = AgentGuest.call(context, request, 20_000, trusted = true)
|
||||
check(result.optBoolean("ok") && result.optInt("exitCode", -1) == 0) { "Close the GOG game before maintenance" }
|
||||
}
|
||||
}
|
||||
|
||||
private fun transfer(context: Context, proposal: Proposal, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean, callback: GogDownloadManager.Callback? = null) {
|
||||
val token = GogContent.token(context)
|
||||
var patches = proposal.deltas
|
||||
var previousWire = 0L
|
||||
for (attempt in 0..4) {
|
||||
if (stop.get()) return
|
||||
val links = GogContent.links(proposal.target, GogContent.token(context))
|
||||
val patchLinks = if (patches.length() > 0) runCatching { GogContent.links(proposal.target, token, patches = true) }.getOrElse { patches = JSONArray(); JSONObject() } else JSONObject()
|
||||
val plan = JSONObject().put("files", proposal.target.files).put("oldFiles", proposal.before.files)
|
||||
.put("patches", patches).put("links", links).put("patchLinks", patchLinks).put("downloadBytes", proposal.downloadBytes)
|
||||
val optimized = GogNative.isAvailable()
|
||||
val remaining = GogEstimate.calculate(proposal.folder, proposal.before, proposal.target, patches, reuseChunks = optimized).required
|
||||
check(!StoreInstallRoot.insufficientSpace(remaining, StoreInstallRoot.availableBytes(proposal.folder))) { "Not enough free space for remaining GOG maintenance" }
|
||||
handle?.diskSize(remaining)
|
||||
if (!optimized) {
|
||||
try { GogFallback.transfer(proposal.folder, plan, handle, stop, callback); return }
|
||||
catch (e: Exception) {
|
||||
if (stop.get()) return
|
||||
if (attempt == 4 || Regex("HTTP (401|403|404|500)").find(e.message.orEmpty()) == null) throw e
|
||||
handle?.log("gog: refreshing file-download links; verified replacements are retained")
|
||||
continue
|
||||
}
|
||||
}
|
||||
val latch = CountDownLatch(1)
|
||||
var runWire = 0L
|
||||
var success = false; var expired = false; var failure = "GOG download failed"
|
||||
val listener = object : GogNative.Listener {
|
||||
override fun onProgress(bytesDone: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, file: String, fileBytes: Long, verified: Boolean) {
|
||||
handle?.stage(if (verified) DownloadStage.VERIFY else DownloadStage.INSTALL)
|
||||
handle?.stageProgress(filesDone.toLong(), filesTotal.toLong(), filesDone, filesTotal)
|
||||
callback?.onStage(if (verified) "verify" else "install", filesDone.toLong(), filesTotal.toLong(), filesDone, filesTotal)
|
||||
}
|
||||
override fun onBytes(bytesDone: Long, bytesTotal: Long) {
|
||||
runWire = bytesDone
|
||||
handle?.progress(previousWire + bytesDone, (previousWire + bytesTotal).coerceAtLeast(previousWire + bytesDone))
|
||||
callback?.onBytes(previousWire + bytesDone, (previousWire + bytesTotal).coerceAtLeast(previousWire + bytesDone), 0)
|
||||
}
|
||||
override fun onLog(line: String) { handle?.log(line); callback?.onLog(line) }
|
||||
override fun onMaintenance(networkBytes: Long, reusedBytes: Long, appliedBytes: Long) { handle?.maintenance(reusedBytes, appliedBytes) }
|
||||
override fun onComplete(ok: Boolean, cancelled: Boolean, linkExpiry: Boolean, error: String, bytesWritten: Long, filesDone: Int) {
|
||||
success = ok; expired = linkExpiry; failure = error; latch.countDown()
|
||||
}
|
||||
}
|
||||
val native = GogNative.start(2, arrayOf(plan.toString()), emptyArray(), proposal.folder.path, emptyArray(), "", 1, 1, false, "gog maintenance", listener)
|
||||
check(native != 0L) { "GOG native engine could not start" }
|
||||
try { while (!latch.await(200, TimeUnit.MILLISECONDS)) if (stop.get()) GogNative.cancel(native) }
|
||||
finally { GogNative.release(native) }
|
||||
if (stop.get()) return
|
||||
if (success) {
|
||||
for (file in proposal.target.files.objects()) if (!file.optBoolean("directory") && file.optString("md5").isBlank() && file.optString("sha256").isBlank())
|
||||
file.put("sha256", GogFiles.hash(GogFiles.inside(proposal.folder, file.getString("path")), "SHA-256"))
|
||||
return
|
||||
}
|
||||
if (!expired || attempt == 4) error(failure)
|
||||
previousWire += runWire
|
||||
handle?.log("gog: refreshing expired download links; validated files and chunks are retained")
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun installContent(context: Context, game: GogGame, folder: File, builds: JSONObject, language: String,
|
||||
callback: GogDownloadManager.Callback, cancelled: AtomicBoolean): GogDownloadManager.Result? {
|
||||
val build = GogBuild.select(builds) ?: return null
|
||||
folder.mkdirs()
|
||||
val old = GogInstallRecord(game.gameId, "depot", language = language)
|
||||
val target = GogContent.snapshot(old, build, GogContent.token(context))
|
||||
GogFiles.validate(target.files, folder)
|
||||
val bytes = target.files.objects().sumOf { it.optJSONArray("chunks")?.objects()?.sumOf { c -> c.optLong("compressedSize") }?.takeIf { n -> n > 0 } ?: it.optLong("size") }
|
||||
val disk = target.files.objects().sumOf { it.optLong("size") }
|
||||
check(!StoreInstallRoot.insufficientSpace(disk, StoreInstallRoot.availableBytes(folder))) { "Not enough free space for GOG installation" }
|
||||
callback.onSizes(bytes, disk)
|
||||
transfer(context, Proposal(folder, old, target, GogOperation.UPDATE, bytes, disk), null, cancelled, callback)
|
||||
if (cancelled.get()) return null
|
||||
target.write(folder)
|
||||
val result = GogDownloadManager.Result(GogDownloadManager.pickExe(folder, null, game.title), build.id, disk)
|
||||
result.language = target.language
|
||||
result.dependencies = target.manifest.optJSONArray("dependencies")?.strings().orEmpty()
|
||||
result.dependenciesRead = true
|
||||
return result
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun captureDepot(id: String, folder: File, build: String, buildsJson: String, manifest: JSONObject, depots: JSONArray, language: String) {
|
||||
val selected = GogBuild.select(JSONObject(buildsJson), pinned = build)
|
||||
val files = JSONArray()
|
||||
for (depot in depots.strings()) for (item in JSONObject(depot).getJSONObject("depot").getJSONArray("items").objects()) {
|
||||
val chunks = item.optJSONArray("chunks") ?: continue
|
||||
files.put(JSONObject().put("path", item.getString("path").replace('\\', '/')).put("size", chunks.objects().sumOf { it.optLong("size") })
|
||||
.put("md5", item.optString("md5")).put("chunks", chunks).put("product", id))
|
||||
}
|
||||
GogFiles.validate(files, folder)
|
||||
GogInstallRecord(id, "depot", 2, build, selected?.version.orEmpty(), selected?.branch.orEmpty(), language,
|
||||
manifest = GogContent.sanitize(manifest), files = files).write(folder)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun captureOffline(id: String, folder: File, downloads: JSONObject) {
|
||||
val selected = GogOfflineDownload.parse(downloads, "installers").firstOrNull() ?: return
|
||||
GogInstallRecord(id, "offline", version = selected.version, language = selected.language).write(folder)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ object GogNative {
|
||||
|
||||
fun onBytes(bytesDone: Long, bytesTotal: Long)
|
||||
|
||||
fun onMaintenance(networkBytes: Long, reusedBytes: Long, appliedBytes: Long)
|
||||
|
||||
fun onLog(line: String)
|
||||
|
||||
fun onComplete(success: Boolean, cancelled: Boolean, linkExpiry: Boolean, error: String, bytesWritten: Long, filesDone: Int)
|
||||
@@ -26,7 +28,7 @@ object GogNative {
|
||||
fun isAvailable(): Boolean {
|
||||
available?.let { return it }
|
||||
val ok = try {
|
||||
StoresNative.ensureLoaded() && nativeProbe() == 1
|
||||
StoresNative.ensureLoaded() && nativeProbe() == 2
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "native GOG engine unavailable: ${t.javaClass.simpleName}: ${t.message}")
|
||||
false
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.agent.AgentGuest
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal object GogOffline {
|
||||
private const val HELPER = "/usr/local/bin/droiddeck-gog-maintenance"
|
||||
|
||||
internal data class Layout(val source: File, val prefix: String)
|
||||
|
||||
internal fun layout(extracted: File, installed: File, id: String, executable: String): Layout {
|
||||
val nested = executable.startsWith("app/", true) && !File(installed, "goggame-$id.info").isFile
|
||||
return Layout(extracted, if (nested) "app/" else "")
|
||||
}
|
||||
|
||||
internal fun validateDepotInstaller(extracted: File, target: GogInstallRecord) {
|
||||
if (target.source != "depot") return
|
||||
val builds = listOf(extracted, File(extracted, "app")).map { GogInstallRecord.authenticBuild(it, target.id) }.filter { it.isNotBlank() }
|
||||
require(builds.isNotEmpty() && builds.all { it == target.build } && target.build.isNotBlank()) {
|
||||
"The offline installer does not identify the selected depot build. Use Update to preserve installed DLC."
|
||||
}
|
||||
}
|
||||
|
||||
private fun download(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean): File {
|
||||
val patch = proposal.patch ?: error("GOG download selection is missing")
|
||||
val root = File(GogFiles.dir(proposal.folder), "downloads").apply { mkdirs() }
|
||||
var first: File? = null; var bytes = 0L
|
||||
for ((index, part) in patch.parts.withIndex()) {
|
||||
if (stop.get()) return first ?: File(root, "cancelled")
|
||||
val resolved = GogDownloadManager.resolveRedirect(part.url, GogContent.token(context)) ?: error("The GOG download link is unavailable")
|
||||
val serverName = GogContent.downloadFilename(resolved).takeIf { it.endsWith(".exe", true) || it.endsWith(".bin", true) }
|
||||
val name = part.name.ifBlank { serverName ?: error("GOG did not provide the installer part filename") }
|
||||
require('/' !in name && '\\' !in name && name !in setOf(".", "..")) { "Invalid GOG installer filename" }
|
||||
val file = GogFiles.inside(root, name)
|
||||
val receipt = File(root, "part-$index.json")
|
||||
val saved = GogFiles.read(receipt)
|
||||
val complete = file.isFile && (part.size <= 0 || file.length() == part.size) && when {
|
||||
part.md5.isNotBlank() -> GogFiles.hash(file).equals(part.md5, true)
|
||||
saved?.optString("id") == part.id && saved.optString("filename") == name -> GogFiles.hash(file, "SHA-256") == saved.optString("sha256")
|
||||
else -> false
|
||||
}
|
||||
if (!complete) {
|
||||
val staging = GogFiles.inside(root, "$name.partial")
|
||||
GogFallback.download(listOf(resolved), staging, part.size, stop, { n -> bytes += n; handle.progress(bytes, proposal.downloadBytes.coerceAtLeast(bytes)) })
|
||||
if (stop.get()) return first ?: file
|
||||
if (part.md5.isNotBlank()) check(GogFiles.hash(staging).equals(part.md5, true)) { "GOG installer checksum mismatch" }
|
||||
GogFiles.replace(staging, file)
|
||||
GogFiles.write(receipt, JSONObject().put("id", part.id).put("filename", name).put("sha256", GogFiles.hash(file, "SHA-256")))
|
||||
}
|
||||
if (index == 0) { check(file.extension.equals("exe", true)) { "GOG patch has no setup executable" }; first = file }
|
||||
}
|
||||
return first ?: error("GOG download has no files")
|
||||
}
|
||||
|
||||
fun refresh(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean) {
|
||||
val installer = download(context, proposal, handle, stop)
|
||||
if (stop.get()) return
|
||||
val extracted = File(GogFiles.dir(proposal.folder), "extracted").apply { mkdirs() }
|
||||
val source = AddedGames.guestPath(context, installer) ?: error("The GOG installer is not visible to Linux")
|
||||
val target = AddedGames.guestPath(context, extracted) ?: error("The GOG staging folder is not visible to Linux")
|
||||
handle.stage(DownloadStage.INSTALL, "Extracting the full offline installer")
|
||||
val rc = GuestCommand.run(context, listOf("/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", target, source),
|
||||
extraBinds = StoreInstallRoot.externalBindSpecs(context), cancelled = stop, logName = "gog-refresh", onLine = handle::log)
|
||||
if (stop.get()) return
|
||||
check(rc == 0) { "GOG installer extraction failed (exit $rc)" }
|
||||
applyRefresh(proposal, extracted, handle, stop)
|
||||
}
|
||||
|
||||
internal fun applyRefresh(proposal: GogMaintenance.Proposal, extracted: File, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean) {
|
||||
validateDepotInstaller(extracted, proposal.target)
|
||||
val sidecar = StoreGameSidecar.read(proposal.folder) ?: error("The original GOG settings are missing")
|
||||
val layout = layout(extracted, proposal.folder, proposal.before.id, sidecar.exe)
|
||||
val files = layout.source.walkTopDown().onEnter { directory ->
|
||||
check(!java.nio.file.Files.isSymbolicLink(directory.toPath())) { "GOG installer contains a symbolic link" }
|
||||
directory.parentFile != extracted || directory.name !in setOf("tmp", "commonappdata", "userappdata", "localappdata")
|
||||
}.filter { it != layout.source && it != File(extracted, "app") }.map { file ->
|
||||
check(!java.nio.file.Files.isSymbolicLink(file.toPath()))
|
||||
val relative = file.relativeTo(layout.source).invariantSeparatorsPath.removePrefix("app/")
|
||||
JSONObject().put("path", layout.prefix + relative)
|
||||
.put("size", if (file.isDirectory) 0 else file.length()).put("directory", file.isDirectory)
|
||||
.put("md5", if (file.isDirectory) "" else GogFiles.hash(file)).put("product", proposal.before.id) to file
|
||||
}.toList().groupBy { it.first.getString("path") }.map { (_, entries) ->
|
||||
check(entries.size == 1 || entries.all { it.first.getBoolean("directory") }) { "GOG installer has conflicting file locations" }
|
||||
entries.first()
|
||||
}
|
||||
check(files.any { !it.first.getBoolean("directory") }) { "GOG installer contained no game files" }
|
||||
val inventory = JSONArray(files.map { it.first })
|
||||
GogFiles.validate(inventory, proposal.folder)
|
||||
val executable = sidecar.exe.replace('\\', '/')
|
||||
check(files.any { !it.first.getBoolean("directory") && it.first.getString("path").equals(executable, true) } ||
|
||||
proposal.before.verified && proposal.before.files.length() > 0 &&
|
||||
proposal.before.files.objects().none { it.getString("path").equals(executable, true) } && GogFiles.inside(proposal.folder, executable).isFile) {
|
||||
"The offline installer did not extract the game's executable. No installed files were changed."
|
||||
}
|
||||
val installed = proposal.target.copy(files = inventory)
|
||||
GogFiles.write(File(GogFiles.dir(proposal.folder), "refresh-target.json"), installed.json())
|
||||
for ((index, entry) in files.withIndex()) {
|
||||
if (stop.get()) return
|
||||
val (file, sourceFile) = entry
|
||||
val destination = GogFiles.inside(proposal.folder, file.getString("path"))
|
||||
if (file.getBoolean("directory")) java.nio.file.Files.createDirectories(destination.toPath()) else {
|
||||
destination.parentFile!!.mkdirs()
|
||||
GogFiles.replace(sourceFile, destination)
|
||||
}
|
||||
handle?.stageProgress((index + 1).toLong(), files.size.toLong())
|
||||
}
|
||||
if (proposal.target.source != "depot") {
|
||||
val targetPaths = files.mapTo(HashSet()) { it.first.getString("path").lowercase(java.util.Locale.ROOT) }
|
||||
for (old in proposal.before.files.objects()) if (old.getString("path").lowercase(java.util.Locale.ROOT) !in targetPaths && GogFiles.matches(proposal.folder, old))
|
||||
check(GogFiles.inside(proposal.folder, old.getString("path")).delete())
|
||||
installed.write(proposal.folder)
|
||||
}
|
||||
}
|
||||
|
||||
fun apply(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean, onApplying: () -> Unit): Boolean {
|
||||
check(GogFiles.read(GogFiles.journal(proposal.folder))?.optString("phase") in setOf("download", "patch-ready")) {
|
||||
"The patch result needs recovery. Inspect the installer or use a full offline refresh; the patch will not be run again."
|
||||
}
|
||||
val installer = download(context, proposal, handle, stop)
|
||||
if (stop.get()) return false
|
||||
val setup = GogContent.setupFiles(proposal.before, GogContent.token(context))
|
||||
if (setup != null) {
|
||||
GogFallback.transfer(proposal.folder, JSONObject().put("files", setup.first).put("links", setup.second)
|
||||
.put("downloadBytes", setup.first.objects().sumOf { it.getJSONArray("chunks").objects().sumOf { chunk -> chunk.getLong("compressedSize") } }), handle, stop)
|
||||
if (stop.get()) return false
|
||||
}
|
||||
val added = AddedGames.single(context, proposal.folder.path) ?: error("The GOG game shortcut is unavailable")
|
||||
val id = (added.steamAppId?.toLong() ?: added.appId) and 0xffffffffL
|
||||
val folder = AddedGames.guestPath(context, proposal.folder) ?: error("The GOG folder is unavailable to Linux")
|
||||
val executable = AddedGames.guestPath(context, installer) ?: error("The GOG patch is unavailable to Linux")
|
||||
context.startActivity(android.content.Intent(context, com.droiddeck.launcher.SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, if (SessionState.running) SessionState.mode else SessionService.MODE_DESKTOP)
|
||||
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP or android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
||||
val deadline = System.currentTimeMillis() + 120_000
|
||||
while (AgentGuest.hello(context) == null && System.currentTimeMillis() < deadline) { if (stop.get()) return false; Thread.sleep(250) }
|
||||
check(AgentGuest.hello(context) != null) { "The Linux session did not become ready; open it and retry" }
|
||||
val journal = GogFiles.read(GogFiles.journal(proposal.folder)) ?: error("GOG patch journal is missing")
|
||||
journal.put("phase", "patch-ready")
|
||||
File(GogFiles.dir(proposal.folder), "patch-status.json").delete()
|
||||
GogFiles.write(GogFiles.journal(proposal.folder), journal)
|
||||
val request = JSONObject().put("kind", "exec").put("timeout", 15)
|
||||
.put("env", JSONObject().put("DROIDDECK_GOG_DESKTOP", if (SessionState.mode == SessionService.MODE_DESKTOP) "1" else "0"))
|
||||
.put("argv", JSONArray(listOf(HELPER, "start", folder, id.toString(), executable, added.guestExe)))
|
||||
if (stop.get()) return false
|
||||
onApplying()
|
||||
val response = AgentGuest.call(context, request, 20_000, trusted = true)
|
||||
check(response.optBoolean("ok") && response.optInt("exitCode", -1) == 0) { "The GOG patch installer could not start; inspect the GOG log" }
|
||||
handle.stage(DownloadStage.INSTALL, "Use the Linux session to finish or cancel the patch installer")
|
||||
var nextStatus = System.currentTimeMillis() + 5_000
|
||||
while (true) {
|
||||
val status = GogFiles.read(File(GogFiles.dir(proposal.folder), "patch-status.json"))
|
||||
if (status?.optString("state") in setOf("done", "failed", "uncertain")) {
|
||||
check(status?.optString("state") == "done") { status?.optString("reason") ?: "GOG patch failed" }
|
||||
break
|
||||
}
|
||||
check(SessionState.running) { "The patch session ended. Its result needs recovery; the patch will not be rerun automatically." }
|
||||
check(!SessionState.suspended) { "The patch session was suspended. Resume it and verify recovery before retrying." }
|
||||
if (System.currentTimeMillis() >= nextStatus) {
|
||||
val query = JSONObject().put("kind", "exec").put("timeout", 5).put("argv", JSONArray(listOf(HELPER, "status", folder)))
|
||||
val answer = AgentGuest.call(context, query, 10_000, trusted = true)
|
||||
check(answer.optBoolean("ok") && answer.optInt("exitCode", -1) == 0) { "The patch helper could not be reached. Resume the Linux session and verify recovery." }
|
||||
nextStatus = System.currentTimeMillis() + 5_000
|
||||
}
|
||||
Thread.sleep(500)
|
||||
}
|
||||
val info = GogFiles.read(File(proposal.folder, "goggame-${proposal.before.id}.info"))
|
||||
val version = info?.optString("versionName").orEmpty()
|
||||
val build = GogInstallRecord.authenticBuild(proposal.folder, proposal.before.id)
|
||||
var record = proposal.target.copy(build = build, version = version, files = JSONArray(), manifest = JSONObject(), verified = false)
|
||||
record.write(proposal.folder)
|
||||
if (build.isNotBlank()) {
|
||||
record = runCatching {
|
||||
val token = GogContent.token(context)
|
||||
val target = GogBuild.select(GogContent.builds(record.id, token), pinned = build)
|
||||
val snapshot = target?.let { GogContent.snapshot(record, it, token) }
|
||||
snapshot?.takeIf { it.files.objects().all { f -> f.optBoolean("directory") || GogFiles.matches(proposal.folder, f) } } ?: record
|
||||
}.getOrDefault(record)
|
||||
}
|
||||
record.write(proposal.folder)
|
||||
if (!record.verified) {
|
||||
val before = StoreGameSidecar.read(proposal.folder) ?: error("The GOG installation record is missing")
|
||||
before.copy(installVersion = "", state = StoreGameSidecar.STATE_UPDATING).write(proposal.folder)
|
||||
val operation = GogFiles.read(GogFiles.journal(proposal.folder))!!
|
||||
GogFiles.write(GogFiles.journal(proposal.folder), operation.put("phase", "patch-uncertain"))
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreBackend
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreSizes
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
@@ -18,6 +19,8 @@ import java.io.File
|
||||
object ItchBackend : StoreBackend {
|
||||
override val store: Store = Store.ITCH
|
||||
|
||||
override fun maintenanceAdapter(): StoreMaintenanceAdapter = ItchMaintenanceAdapter
|
||||
|
||||
override fun signIn(context: Context) {
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(ItchApi.KEYS_PAGE)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
|
||||
@@ -11,14 +11,17 @@ import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZFile
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile
|
||||
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream
|
||||
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
|
||||
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
@@ -31,6 +34,7 @@ internal class ItchInstaller(
|
||||
private val app: Context,
|
||||
private val item: CatalogItem,
|
||||
private val folder: File,
|
||||
private val maintenanceTarget: JSONObject? = null,
|
||||
) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
private var work: File = folder
|
||||
@@ -55,18 +59,34 @@ internal class ItchInstaller(
|
||||
val upload = (if (chosen.isBlank()) ItchUploads.windows(uploads) else ItchUploads.byId(uploads, chosen))
|
||||
?: throw IllegalStateException(app.getString(R.string.stores_itch_no_upload))
|
||||
val uploadId = upload.optString("id")
|
||||
val version = ItchUploads.updatedAt(upload)
|
||||
val filename = ItchUploads.filename(upload)
|
||||
val size = ItchUploads.size(upload)
|
||||
maintenanceTarget?.let {
|
||||
require(it.optInt("schema") == 1 && it.optString("gameId") == gameId &&
|
||||
it.optString("downloadKeyId") == downloadKeyId && it.optString("uploadId") == uploadId &&
|
||||
it.optString("updatedAt") == version && it.optString("filename") == filename && it.optLong("size") == size) {
|
||||
"The pinned itch.io upload changed; prepare maintenance again"
|
||||
}
|
||||
}
|
||||
val scratch = StoreInstallRoot.scratchDir(app, Store.ITCH, item.id)
|
||||
scratch.mkdirs()
|
||||
val archive = File(scratch, filename.ifBlank { "download.bin" })
|
||||
val exe = try {
|
||||
handle.stage(DownloadStage.DOWNLOAD)
|
||||
download(key, downloadKeyId, uploadId, upload.optString("updated_at", upload.optString("updatedAt")), archive, size, handle)
|
||||
download(key, downloadKeyId, uploadId, version, archive, size, handle)
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL)
|
||||
install(archive, filename, handle, resuming)
|
||||
} catch (t: Throwable) {
|
||||
if (maintenanceTarget != null) {
|
||||
runCatching { handle.interruptible(true) }
|
||||
val beforeSidecar = previous
|
||||
val recoverableCommit = runCatching { ItchStaging.recover(folder) }.getOrDefault(true)
|
||||
if (t is ItchStaging.PreflightConflict && !recoverableCommit && beforeSidecar != null) {
|
||||
runCatching { StoreMaintenance.complete(app, InstalledStoreGame(beforeSidecar, folder)) }
|
||||
}
|
||||
}
|
||||
if (!cancelled.get()) dropCaches(scratch)
|
||||
throw t
|
||||
}
|
||||
@@ -77,6 +97,15 @@ internal class ItchInstaller(
|
||||
}
|
||||
archive.delete()
|
||||
StoreInstalls.deleteTree(scratch)
|
||||
if (maintenanceTarget != null) {
|
||||
val beforeSidecar = previous ?: throw IllegalStateException("The installed itch.io sidecar disappeared")
|
||||
try {
|
||||
StoreMaintenance.complete(app, InstalledStoreGame(beforeSidecar, folder), version,
|
||||
beforeSidecar.extra + ("uploadId" to maintenanceTarget.optString("uploadId")))
|
||||
ItchUpdates.applied(app, item.key)
|
||||
} finally { handle.interruptible(true) }
|
||||
return folder.path
|
||||
}
|
||||
val sidecar = StoreGameSidecar(
|
||||
store = Store.ITCH,
|
||||
id = item.id,
|
||||
@@ -84,13 +113,14 @@ internal class ItchInstaller(
|
||||
exe = exe,
|
||||
args = previous?.args.orEmpty(),
|
||||
env = previous?.env.orEmpty(),
|
||||
installVersion = upload.optString("updated_at", upload.optString("updatedAt")),
|
||||
installVersion = version,
|
||||
installedAt = System.currentTimeMillis(),
|
||||
cover = item.imageUrl,
|
||||
hero = item.imageUrl,
|
||||
extra = mapOf("gameId" to gameId, "downloadKeyId" to downloadKeyId, "uploadId" to uploadId),
|
||||
cloud = false,
|
||||
)
|
||||
if (!updating) ItchStaging.writeInventory(folder, ItchStaging.inventory(folder))
|
||||
StoreInstalls.complete(app, folder, sidecar) { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }
|
||||
ItchUpdates.applied(app, item.key)
|
||||
return folder.path
|
||||
@@ -98,7 +128,13 @@ internal class ItchInstaller(
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (deleteFiles) dropCaches(StoreInstallRoot.scratchDir(app, Store.ITCH, item.id))
|
||||
if (deleteFiles) {
|
||||
dropCaches(StoreInstallRoot.scratchDir(app, Store.ITCH, item.id))
|
||||
if (maintenanceTarget != null) {
|
||||
val phase = runCatching { StoreMaintenance.readOperation(folder)?.optString("phase") }.getOrNull()
|
||||
if (phase in setOf("queued", "download")) runCatching { StoreMaintenance.clearOperation(folder) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun dropCaches(scratch: File) {
|
||||
@@ -182,6 +218,7 @@ internal class ItchInstaller(
|
||||
work = if (updating) File(folder, ItchStaging.DIR) else folder
|
||||
if (updating) ItchStaging.delete(work)
|
||||
work.mkdirs()
|
||||
val availableBeforeExtraction = if (maintenanceTarget != null) StoreInstallRoot.availableBytes(folder) else StoreInstallRoot.SPACE_UNKNOWN
|
||||
if (resuming) clearPartialInstall()
|
||||
val exe = try {
|
||||
when (val kind = sniff(archive, filename)) {
|
||||
@@ -193,8 +230,10 @@ internal class ItchInstaller(
|
||||
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
|
||||
else -> copy(archive, File(work, filename.ifBlank { "game" }))
|
||||
}
|
||||
val hint = filename.substringBeforeLast('.')
|
||||
StoreExe.pick(work, hint.ifBlank { null }, item.title)
|
||||
if (maintenanceTarget != null) previous?.exe.orEmpty() else {
|
||||
val hint = filename.substringBeforeLast('.')
|
||||
StoreExe.pick(work, hint.ifBlank { null }, item.title)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
if (updating) ItchStaging.delete(work)
|
||||
throw t
|
||||
@@ -204,6 +243,42 @@ internal class ItchInstaller(
|
||||
if (updating) ItchStaging.delete(work)
|
||||
return null
|
||||
}
|
||||
if (maintenanceTarget != null) {
|
||||
val stagedBytes = ItchStaging.regularFileBytes(work)
|
||||
?: throw IllegalStateException("Could not measure the extracted itch.io archive")
|
||||
val requiredBytes = ItchStaging.additionalBytesRequired(stagedBytes, backupExtraBytes = 0L)
|
||||
handle.diskSize(requiredBytes)
|
||||
if (StoreInstallRoot.insufficientSpace(requiredBytes, availableBeforeExtraction)) {
|
||||
throw IllegalStateException(app.getString(R.string.stores_storage_insufficient,
|
||||
com.droiddeck.launcher.stores.formatBytes(requiredBytes),
|
||||
com.droiddeck.launcher.stores.formatBytes(availableBeforeExtraction)))
|
||||
}
|
||||
}
|
||||
if (updating && maintenanceTarget != null) {
|
||||
handle.interruptible(false)
|
||||
synchronized(commit) {
|
||||
if (cancelled.get()) {
|
||||
handle.interruptible(true)
|
||||
ItchStaging.delete(work)
|
||||
return null
|
||||
}
|
||||
val old = previous ?: throw IllegalStateException("The installed itch.io sidecar disappeared")
|
||||
val game = InstalledStoreGame(old, folder)
|
||||
StoreMaintenance.withApplyLease(game) {
|
||||
val targetInventory = ItchStaging.inventory(work)
|
||||
val savedInventory = ItchStaging.readInventoryIfPresent(folder)
|
||||
val targetUploadId = maintenanceTarget?.optString("uploadId").orEmpty()
|
||||
val targetVersion = maintenanceTarget?.optString("updatedAt").orEmpty()
|
||||
val installedExactUpload = targetUploadId.isNotBlank() && old.extra["uploadId"] == targetUploadId &&
|
||||
old.installVersion == targetVersion
|
||||
val managed = ItchStaging.previousInventory(savedInventory, targetInventory, installedExactUpload, old.exe)
|
||||
ItchStaging.commit(work, folder, managed, onCommitted = { next ->
|
||||
ItchStaging.writeInventory(folder, next)
|
||||
})
|
||||
}
|
||||
}
|
||||
return exe
|
||||
}
|
||||
if (updating) synchronized(commit) {
|
||||
if (cancelled.get()) {
|
||||
ItchStaging.delete(work)
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.SavedQueue
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
|
||||
import com.droiddeck.launcher.stores.maintenance.RecoveryState
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
internal object ItchMaintenanceAdapter : StoreMaintenanceAdapter {
|
||||
override val store = Store.ITCH
|
||||
private val exactTargets = ConcurrentHashMap<String, JSONObject>()
|
||||
private val exactCheckedAt = ConcurrentHashMap<String, Long>()
|
||||
|
||||
override fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> {
|
||||
val result = linkedSetOf(MaintenanceAction.REFRESH)
|
||||
if (StoreMaintenance.check(game).state == MaintenanceCheckState.AVAILABLE) result.add(MaintenanceAction.UPDATE)
|
||||
val exact = exactTargets[game.key]
|
||||
if (System.currentTimeMillis() - (exactCheckedAt[game.key] ?: 0L) < 30 * 60_000L &&
|
||||
!game.sidecar.installVersion.isBlank() && exact != null && exact.optString("uploadId") == game.sidecar.extra["uploadId"] &&
|
||||
exact.optString("updatedAt") == game.sidecar.installVersion) result.add(MaintenanceAction.REPAIR)
|
||||
return result
|
||||
}
|
||||
|
||||
override fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck {
|
||||
val key = ItchAuth.key(context)
|
||||
if (key.isBlank()) { forgetExact(game.key); return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "Sign in to itch.io to check uploads") }
|
||||
val gameId = game.sidecar.extra["gameId"].orEmpty()
|
||||
if (gameId.isBlank()) { forgetExact(game.key); return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "The installed itch.io game has no game ID") }
|
||||
val uploads = ItchApi.uploads(key, gameId, game.sidecar.extra["downloadKeyId"].orEmpty())
|
||||
?: run { forgetExact(game.key); return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "itch.io upload check failed") }
|
||||
if (game.sidecar.installVersion.isBlank()) {
|
||||
forgetExact(game.key)
|
||||
return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "The installed itch.io upload version is unknown; use Refresh")
|
||||
}
|
||||
val uploadId = game.sidecar.extra["uploadId"].orEmpty()
|
||||
val installed = ItchUploads.byId(uploads, uploadId)
|
||||
val exact = installed?.takeIf { game.sidecar.installVersion.isNotBlank() && ItchUploads.updatedAt(it) == game.sidecar.installVersion }
|
||||
if (exact != null) {
|
||||
exactTargets[game.key] = targetJson(game, exact)
|
||||
exactCheckedAt[game.key] = System.currentTimeMillis()
|
||||
} else forgetExact(game.key)
|
||||
val update = ItchUpdates.evaluate(uploads, uploadId, game.sidecar.installVersion)
|
||||
return if (update == null) MaintenanceCheck(MaintenanceCheckState.CURRENT, game.sidecar.installVersion)
|
||||
else MaintenanceCheck(MaintenanceCheckState.AVAILABLE, update.updatedAt, if (update.replaced) "The installed upload was replaced" else "A newer upload is available")
|
||||
}
|
||||
|
||||
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal {
|
||||
val token = ItchAuth.key(context)
|
||||
require(token.isNotBlank()) { "Sign in to itch.io to maintain this game" }
|
||||
val extra = game.sidecar.extra
|
||||
val gameId = extra["gameId"].orEmpty()
|
||||
val keyId = extra["downloadKeyId"].orEmpty()
|
||||
require(gameId.isNotBlank()) { "The installed itch.io game has no game ID" }
|
||||
val uploads = ItchApi.uploads(token, gameId, keyId) ?: throw IllegalStateException("itch.io upload check failed")
|
||||
val currentUpload = ItchUploads.byId(uploads, extra["uploadId"].orEmpty())
|
||||
val chosenUpload = when (action) {
|
||||
MaintenanceAction.REPAIR -> currentUpload?.takeIf { game.sidecar.installVersion.isNotBlank() && ItchUploads.updatedAt(it) == game.sidecar.installVersion }
|
||||
?: throw IllegalStateException("The exact installed upload is no longer available; use Refresh for the current upload")
|
||||
MaintenanceAction.UPDATE -> {
|
||||
val next = ItchUpdates.evaluate(uploads, extra["uploadId"].orEmpty(), game.sidecar.installVersion)
|
||||
?: throw IllegalStateException("No newer itch.io upload is available")
|
||||
ItchUploads.byId(uploads, next.uploadId) ?: throw IllegalStateException("The selected itch.io upload disappeared")
|
||||
}
|
||||
MaintenanceAction.REFRESH -> currentUpload ?: ItchUploads.newestWindows(uploads)
|
||||
?: throw IllegalStateException("No Windows itch.io upload is available")
|
||||
else -> throw IllegalArgumentException("Unsupported itch.io maintenance action")
|
||||
}
|
||||
val target = targetJson(game, chosenUpload)
|
||||
val id = target.optString("uploadId")
|
||||
val stamp = target.optString("updatedAt")
|
||||
val label = when (action) {
|
||||
MaintenanceAction.REPAIR -> "installed upload $id ($stamp)"
|
||||
MaintenanceAction.UPDATE -> "upload $id ($stamp)"
|
||||
else -> if (id == extra["uploadId"] && stamp == game.sidecar.installVersion) "current upload $id ($stamp)" else "current upload $id ($stamp); the installed upload is no longer available"
|
||||
}
|
||||
val size = target.optLong("size")
|
||||
return MaintenanceProposal(game.folder, game.sidecar, label, action, size, MaintenanceProposal.UNKNOWN_BYTES,
|
||||
"Downloads one pinned archive. Extracted size and required free space are unknown until download; DroidDeck checks the measured extracted payload before replacing files.", target)
|
||||
}
|
||||
|
||||
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean =
|
||||
enqueuePinned(context, game, proposal.target)
|
||||
|
||||
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) {
|
||||
val target = operation.optJSONObject("target") ?: throw IllegalStateException("itch.io maintenance target is missing")
|
||||
check(enqueuePinned(context, game, target)) { "itch.io maintenance is already queued" }
|
||||
}
|
||||
|
||||
override fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
|
||||
ItchStaging.readInventoryIfPresent(game.folder)
|
||||
val operation = StoreMaintenance.readOperation(game.folder)
|
||||
return if (operation?.optString("phase")?.let { it in setOf("queued", "download", "applying") } == true || ItchStaging.recover(game.folder))
|
||||
MaintenanceRecovery(RecoveryState.RESUMABLE, "Resume the interrupted itch.io archive replacement")
|
||||
else MaintenanceRecovery()
|
||||
}
|
||||
|
||||
private fun enqueuePinned(context: Context, game: InstalledStoreGame, target: JSONObject): Boolean {
|
||||
val item = CatalogItem(
|
||||
Store.ITCH, game.sidecar.id, game.sidecar.title, game.sidecar.hero,
|
||||
tallImageUrl = game.sidecar.cover, isFree = game.sidecar.extra["downloadKeyId"].isNullOrBlank(), owned = true,
|
||||
extra = game.sidecar.extra + mapOf("uploadId" to target.optString("uploadId"),
|
||||
StoreMaintenance.OPERATION_KEY to (StoreMaintenance.readOperation(game.folder)?.optString("operation") ?: MaintenanceAction.REFRESH.name),
|
||||
StoreMaintenance.FOLDER_KEY to game.folder.absolutePath),
|
||||
)
|
||||
val entry = DownloadEntry(Store.ITCH, game.sidecar.id, game.sidecar.title,
|
||||
bytesTotal = target.optLong("size"), location = StoreInstallRoot.labelFor(context, game.folder))
|
||||
return DownloadQueue.enqueueIfIdle(context.applicationContext, entry, onAccepted = {
|
||||
SavedQueue.remember(context.applicationContext, item, null)
|
||||
}) { ItchInstaller(context.applicationContext, item, game.folder, target) }
|
||||
}
|
||||
|
||||
private fun targetJson(game: InstalledStoreGame, upload: JSONObject): JSONObject = JSONObject()
|
||||
.put("schema", 1).put("gameId", game.sidecar.extra["gameId"].orEmpty())
|
||||
.put("downloadKeyId", game.sidecar.extra["downloadKeyId"].orEmpty())
|
||||
.put("uploadId", upload.optString("id"))
|
||||
.put("updatedAt", ItchUploads.updatedAt(upload))
|
||||
.put("filename", ItchUploads.filename(upload))
|
||||
.put("size", ItchUploads.size(upload))
|
||||
|
||||
private fun forgetExact(gameKey: String) {
|
||||
exactTargets.remove(gameKey)
|
||||
exactCheckedAt.remove(gameKey)
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,434 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
import java.security.MessageDigest
|
||||
|
||||
internal object ItchStaging {
|
||||
const val DIR = ".droiddeck-update"
|
||||
const val RECORD = ".droiddeck-store.json"
|
||||
private const val JOURNAL = "itch-commit.json"
|
||||
private const val PROGRESS = "itch-commit-progress.jsonl"
|
||||
private const val INVENTORY = "itch-inventory.json"
|
||||
private const val BACKUPS = "itch-backups"
|
||||
private const val DIRECTORY = "<directory>"
|
||||
|
||||
class PreflightConflict(message: String) : IllegalArgumentException(message)
|
||||
|
||||
fun inventory(root: File): Map<String, String> = linkedMapOf<String, String>().also { out ->
|
||||
fun visit(dir: File, prefix: String) {
|
||||
for (child in dir.listFiles().orEmpty().sortedBy { it.name }) {
|
||||
if (Files.isSymbolicLink(child.toPath())) continue
|
||||
val path = if (prefix.isEmpty()) child.name else "$prefix/${child.name}"
|
||||
if (prefix.isEmpty() && (child.name == RECORD || child.name == DIR || child.name == ".droiddeck-maintenance")) continue
|
||||
if (child.isDirectory) {
|
||||
val children = child.listFiles()
|
||||
if (children != null && children.isEmpty()) out["$path/"] = DIRECTORY
|
||||
else visit(child, path)
|
||||
} else if (child.isFile) out[path] = sha256(child)
|
||||
}
|
||||
}
|
||||
visit(root, "")
|
||||
}
|
||||
|
||||
fun regularFileBytes(root: File): Long? {
|
||||
var total = 0L
|
||||
var readable = true
|
||||
fun visit(dir: File) {
|
||||
if (!readable || Files.isSymbolicLink(dir.toPath())) return
|
||||
val children = dir.listFiles() ?: run { readable = false; return }
|
||||
for (child in children) {
|
||||
if (Files.isSymbolicLink(child.toPath())) continue
|
||||
if (child.isDirectory) visit(child)
|
||||
else if (child.isFile) {
|
||||
val length = runCatching { Files.size(child.toPath()) }.getOrNull()
|
||||
if (length == null || Long.MAX_VALUE - total < length) {
|
||||
readable = false
|
||||
return
|
||||
}
|
||||
total += length
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!root.isDirectory) return null
|
||||
visit(root)
|
||||
return total.takeIf { readable }
|
||||
}
|
||||
|
||||
fun additionalBytesRequired(stagedBytes: Long, backupExtraBytes: Long): Long {
|
||||
require(stagedBytes >= 0L && backupExtraBytes >= 0L)
|
||||
return if (Long.MAX_VALUE - stagedBytes < backupExtraBytes) Long.MAX_VALUE else stagedBytes + backupExtraBytes
|
||||
}
|
||||
|
||||
private fun protectedUserData(relative: String): Boolean = relative.split('/').any {
|
||||
it.lowercase() in setOf("save", "saves", "userdata", "user data", "profiles")
|
||||
} || relative.substringAfterLast('/').substringAfterLast('.', "").lowercase() in setOf("sav", "save")
|
||||
|
||||
fun readInventory(root: File): Map<String, String> = readInventoryIfPresent(root).orEmpty()
|
||||
|
||||
fun previousInventory(
|
||||
saved: Map<String, String>?,
|
||||
target: Map<String, String>,
|
||||
exactLegacyTarget: Boolean,
|
||||
selectedExe: String,
|
||||
): Map<String, String> = (saved ?: if (exactLegacyTarget) target else emptyMap())
|
||||
.filterKeys { it != selectedExe || it in target }
|
||||
|
||||
fun readInventoryIfPresent(root: File): Map<String, String>? {
|
||||
val metadata = File(root, ".droiddeck-maintenance")
|
||||
require(!Files.isSymbolicLink(metadata.toPath())) { "Maintenance metadata directory is a symbolic link" }
|
||||
val file = File(metadata, INVENTORY)
|
||||
require(!Files.isSymbolicLink(file.toPath())) { "itch.io inventory is a symbolic link" }
|
||||
if (!file.exists()) return null
|
||||
require(file.isFile) { "itch.io inventory is not a regular file" }
|
||||
val value = runCatching { JSONObject(file.readText()) }
|
||||
.getOrElse { throw IllegalStateException("itch.io inventory is corrupt", it) }
|
||||
return linkedMapOf<String, String>().apply {
|
||||
value.keys().forEach { path ->
|
||||
val hash = value.optString(path)
|
||||
require(validInventoryEntry(root.canonicalFile, path, hash)) { "itch.io inventory entry is invalid" }
|
||||
put(path, hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun writeInventory(root: File, inventory: Map<String, String>) {
|
||||
val metadata = File(root, ".droiddeck-maintenance")
|
||||
require(!Files.isSymbolicLink(metadata.toPath())) { "Maintenance metadata directory is a symbolic link" }
|
||||
metadata.mkdirs()
|
||||
val file = File(metadata, INVENTORY)
|
||||
require(!Files.isSymbolicLink(file.toPath())) { "itch.io inventory is a symbolic link" }
|
||||
writeJournal(file, JSONObject().apply { inventory.forEach { (path, hash) -> put(path, hash) } })
|
||||
}
|
||||
|
||||
fun commit(
|
||||
from: File,
|
||||
to: File,
|
||||
previous: Map<String, String>,
|
||||
afterEntry: ((Int) -> Unit)? = null,
|
||||
onCommitted: ((Map<String, String>) -> Unit)? = null,
|
||||
): Map<String, String> {
|
||||
require(!Files.isSymbolicLink(to.toPath())) { "The itch.io install folder is a symbolic link" }
|
||||
val root = to.canonicalFile
|
||||
val metadata = File(root, ".droiddeck-maintenance").apply { mkdirs() }
|
||||
require(!Files.isSymbolicLink(metadata.toPath())) { "Maintenance metadata directory is a symbolic link" }
|
||||
val backups = File(metadata, BACKUPS)
|
||||
val journal = File(metadata, JOURNAL)
|
||||
val progress = File(metadata, PROGRESS)
|
||||
val existing = readJournal(journal)
|
||||
val discovered = inventory(from)
|
||||
val existingNext = existing?.getJSONObject("next")
|
||||
val next = existing?.optJSONObject("next")?.let { saved ->
|
||||
linkedMapOf<String, String>().apply {
|
||||
saved.keys().forEach { relative ->
|
||||
val hash = saved.optString(relative)
|
||||
require(validInventoryEntry(root, relative, hash)) { "The interrupted itch.io inventory is invalid" }
|
||||
put(relative, hash)
|
||||
}
|
||||
for ((relative, hash) in discovered) {
|
||||
val becameEmptyAfterMove = hash == DIRECTORY && relative.endsWith('/') &&
|
||||
keys.any { it != relative && it.startsWith(relative) }
|
||||
require(this[relative] == hash || becameEmptyAfterMove) {
|
||||
"The staged itch.io archive does not match the interrupted target"
|
||||
}
|
||||
}
|
||||
}
|
||||
} ?: discovered
|
||||
val files = JSONObject().apply { next.forEach { (path, hash) -> put(path, hash) } }
|
||||
val obsolete = previous.keys.filter { it !in next }.sorted()
|
||||
val stage = from.canonicalFile
|
||||
val paths = obsolete.sortedWith(compareByDescending<String> { it.count { ch -> ch == '/' } }.thenBy { it }) +
|
||||
next.keys.sortedWith(compareBy<String> { it.count { ch -> ch == '/' } }.thenBy { it })
|
||||
val obsoletePlan = JSONObject().apply { obsolete.forEach { put(it, previous[it]) } }
|
||||
val legacyDone = existing?.optJSONObject("done")
|
||||
check(existing == null || existing.optInt("schema") == 1 && existingNext != null && existing.optJSONObject("obsolete") != null) {
|
||||
"An interrupted itch.io replacement has an unsupported journal"
|
||||
}
|
||||
check(existing == null || !existing.has("done") || legacyDone != null) {
|
||||
"An interrupted itch.io progress journal is invalid"
|
||||
}
|
||||
require(!Files.isSymbolicLink(progress.toPath())) { "The itch.io progress log is a symbolic link" }
|
||||
val allowedPaths = next.keys + obsoletePlan.keys().asSequence().toSet()
|
||||
val completed = if (existing != null) readProgress(progress, root, allowedPaths) else linkedSetOf()
|
||||
if (existing != null && legacyDone != null) {
|
||||
validateDone(root, legacyDone, allowedPaths)
|
||||
for (relative in legacyDone.keys().asSequence().filter { legacyDone.optBoolean(it) }) {
|
||||
if (completed.add(relative)) appendProgress(progress, relative)
|
||||
}
|
||||
}
|
||||
require(!Files.isSymbolicLink(backups.toPath())) { "The itch.io backup directory is a symbolic link" }
|
||||
backups.mkdirs()
|
||||
require(!Files.isSymbolicLink(backups.toPath())) { "The itch.io backup directory is a symbolic link" }
|
||||
check(backups.isDirectory) { "The itch.io backup path is not a directory" }
|
||||
for (relative in paths) {
|
||||
val expected = next[relative]
|
||||
if (expected == null) continue
|
||||
val path = relative.removeSuffix("/")
|
||||
val dest = safe(root, path) ?: throw PreflightConflict("Unsafe itch.io archive path: $relative")
|
||||
safe(backups, path) ?: throw PreflightConflict("Unsafe itch.io backup path: $relative")
|
||||
val wasJournaledDone = relative in completed
|
||||
if (expected == DIRECTORY) {
|
||||
if (dest.exists() && !dest.isDirectory) {
|
||||
val oldFileHash = previous[path]
|
||||
if (oldFileHash == null || !dest.isFile || sha256(dest) != oldFileHash)
|
||||
throw PreflightConflict("itch.io archive directory collides with an unmanaged file: $path")
|
||||
}
|
||||
continue
|
||||
}
|
||||
val oldHash = previous[relative]
|
||||
if (protectedUserData(path) && dest.exists()) {
|
||||
if (!((oldHash != null && dest.isFile && sha256(dest) == oldHash) || wasJournaledDone))
|
||||
throw PreflightConflict("itch.io archive collides with untracked or modified user data: $path")
|
||||
}
|
||||
val currentHash = if (dest.isFile) sha256(dest) else null
|
||||
if (currentHash != expected) {
|
||||
val emptyManagedDirectory = dest.isDirectory && !Files.isSymbolicLink(dest.toPath()) && dest.listFiles().isNullOrEmpty()
|
||||
if (dest.exists() && !dest.isFile && !emptyManagedDirectory)
|
||||
throw PreflightConflict("itch.io update collides with an unmanaged directory: $relative")
|
||||
if (dest.exists() && oldHash == null && !emptyManagedDirectory && !wasJournaledDone)
|
||||
throw PreflightConflict("itch.io update collides with an unmanaged file: $relative")
|
||||
require(safe(stage, path)?.isFile == true) { "Staged itch.io file is missing: $relative" }
|
||||
}
|
||||
}
|
||||
val plan = JSONObject().put("schema", 1).put("next", files).put("obsolete", obsoletePlan)
|
||||
if (existing == null || legacyDone != null) {
|
||||
if (existing == null && progress.exists()) check(progress.delete()) { "Could not clear stale itch.io progress log" }
|
||||
writeJournal(journal, plan)
|
||||
}
|
||||
var count = 0
|
||||
for (relative in paths) {
|
||||
val directory = next[relative] == DIRECTORY
|
||||
val path = relative.removeSuffix("/")
|
||||
val expected = next[relative]
|
||||
val oldHash = previous[relative]
|
||||
val wasJournaledDone = relative in completed
|
||||
val dest = safe(root, path)
|
||||
if (dest == null && expected == null) {
|
||||
if (completed.add(relative)) appendProgress(progress, relative)
|
||||
count++
|
||||
afterEntry?.invoke(count)
|
||||
continue
|
||||
}
|
||||
val actualDest = dest ?: throw IllegalStateException("Unsafe itch.io archive path: $relative")
|
||||
val staged = safe(stage, path)
|
||||
val backup = safe(backups, path)
|
||||
if (backup == null && expected == null) {
|
||||
if (completed.add(relative)) appendProgress(progress, relative)
|
||||
count++
|
||||
afterEntry?.invoke(count)
|
||||
continue
|
||||
}
|
||||
val actualBackup = backup ?: throw IllegalStateException("Unsafe itch.io backup path: $relative")
|
||||
if (wasJournaledDone) {
|
||||
val expectedHash = expected.takeUnless { it == DIRECTORY }
|
||||
if (expectedHash != null && actualDest.isFile && sha256(actualDest) == expectedHash) { count++; continue }
|
||||
if (expected == DIRECTORY && actualDest.isDirectory && !Files.isSymbolicLink(actualDest.toPath())) { count++; continue }
|
||||
if (expectedHash == null && expected != DIRECTORY && (!actualDest.isFile || oldHash == null || sha256(actualDest) != oldHash)) { count++; continue }
|
||||
}
|
||||
if (expected == null) {
|
||||
if (oldHash == DIRECTORY) {
|
||||
if (actualDest.isDirectory && !Files.isSymbolicLink(actualDest.toPath()) && actualDest.listFiles().isNullOrEmpty()) actualDest.delete()
|
||||
} else if (actualDest.isFile && oldHash != null && sha256(actualDest) == oldHash) {
|
||||
actualBackup.parentFile?.mkdirs()
|
||||
move(actualDest, actualBackup)
|
||||
}
|
||||
} else if (directory) {
|
||||
require(!Files.isSymbolicLink(actualDest.toPath())) { "itch.io archive directory collides with a symbolic link: $path" }
|
||||
if (actualDest.exists() && !actualDest.isDirectory) {
|
||||
val oldFileHash = previous[path]
|
||||
require(oldFileHash != null && sha256(actualDest) == oldFileHash) { "itch.io archive directory collides with an unmanaged file: $path" }
|
||||
actualBackup.parentFile?.mkdirs()
|
||||
move(actualDest, actualBackup)
|
||||
}
|
||||
check(actualDest.isDirectory || actualDest.mkdirs()) { "Could not create itch.io archive directory: $path" }
|
||||
} else {
|
||||
if (protectedUserData(path) && actualDest.exists()) {
|
||||
require((oldHash != null && actualDest.isFile && sha256(actualDest) == oldHash) || wasJournaledDone) {
|
||||
"itch.io archive collides with untracked or modified user data: $path"
|
||||
}
|
||||
}
|
||||
val currentHash = if (actualDest.isFile) sha256(actualDest) else null
|
||||
if (currentHash == expected) {
|
||||
staged?.delete()
|
||||
} else {
|
||||
val stagedFile = staged?.takeIf { it.isFile } ?: throw IllegalStateException("Staged itch.io file is missing: $relative")
|
||||
val emptyManagedDirectory = actualDest.isDirectory && !Files.isSymbolicLink(actualDest.toPath()) && actualDest.listFiles().isNullOrEmpty()
|
||||
require(!actualDest.exists() || oldHash != null || emptyManagedDirectory || wasJournaledDone) { "itch.io update collides with an unmanaged file: $relative" }
|
||||
if (actualDest.isDirectory && !Files.isSymbolicLink(actualDest.toPath()) && actualDest.listFiles().isNullOrEmpty()) actualDest.delete()
|
||||
require(!actualDest.exists() || actualDest.isFile) { "itch.io update collides with an unmanaged directory: $relative" }
|
||||
require(!Files.isSymbolicLink(actualDest.toPath())) { "itch.io update collides with a symbolic link: $relative" }
|
||||
if (actualDest.exists() && !actualBackup.exists()) {
|
||||
actualBackup.parentFile?.mkdirs()
|
||||
move(actualDest, actualBackup)
|
||||
}
|
||||
actualDest.parentFile?.mkdirs()
|
||||
move(stagedFile, actualDest)
|
||||
check(sha256(actualDest) == expected) { "itch.io replacement failed verification: $relative" }
|
||||
}
|
||||
}
|
||||
if (completed.add(relative)) appendProgress(progress, relative)
|
||||
count++
|
||||
afterEntry?.invoke(count)
|
||||
}
|
||||
onCommitted?.invoke(next)
|
||||
StoreInstallsSafeDelete.delete(from)
|
||||
StoreInstallsSafeDelete.delete(backups)
|
||||
if (progress.exists()) check(progress.delete()) { "Could not remove itch.io progress log" }
|
||||
journal.delete()
|
||||
return next
|
||||
}
|
||||
|
||||
fun recover(to: File): Boolean {
|
||||
require(!Files.isSymbolicLink(to.toPath())) { "The itch.io install folder is a symbolic link" }
|
||||
val root = to.canonicalFile
|
||||
val file = File(root, ".droiddeck-maintenance/$JOURNAL")
|
||||
val state = readJournal(file) ?: return false
|
||||
require(state.optInt("schema") == 1) { "The interrupted itch.io replacement has an unsupported journal" }
|
||||
val next = state.optJSONObject("next") ?: throw IllegalStateException("The interrupted itch.io inventory is missing")
|
||||
val obsolete = state.optJSONObject("obsolete") ?: throw IllegalStateException("The interrupted itch.io cleanup list is missing")
|
||||
for (relative in next.keys()) {
|
||||
require(validInventoryEntry(root, relative, next.optString(relative))) {
|
||||
"The interrupted itch.io inventory is invalid"
|
||||
}
|
||||
}
|
||||
for (relative in obsolete.keys()) {
|
||||
require(validInventoryEntry(root, relative, obsolete.optString(relative))) {
|
||||
"The interrupted itch.io cleanup list is invalid"
|
||||
}
|
||||
}
|
||||
val metadata = file.parentFile
|
||||
val progress = File(metadata, PROGRESS)
|
||||
val allowedPaths = next.keys().asSequence().toSet() + obsolete.keys().asSequence().toSet()
|
||||
readProgress(progress, root, allowedPaths)
|
||||
state.optJSONObject("done")?.let { validateDone(root, it, allowedPaths) }
|
||||
return true
|
||||
}
|
||||
|
||||
fun merge(from: File, to: File, top: Boolean = true) {
|
||||
for (child in from.listFiles().orEmpty()) {
|
||||
if (top && child.name == RECORD) continue
|
||||
val dest = File(to, child.name)
|
||||
val destPath = dest.toPath()
|
||||
if (child.isDirectory && !Files.isSymbolicLink(child.toPath()) && dest.isDirectory && !Files.isSymbolicLink(destPath)) {
|
||||
if (child.isDirectory && !Files.isSymbolicLink(child.toPath()) && dest.isDirectory && !Files.isSymbolicLink(dest.toPath())) {
|
||||
merge(child, dest, false)
|
||||
continue
|
||||
} else {
|
||||
if (Files.isSymbolicLink(dest.toPath())) dest.delete()
|
||||
require(!dest.exists() || child.isDirectory == dest.isDirectory) {
|
||||
"itch.io archive path collides with an existing path: ${child.name}"
|
||||
}
|
||||
require(!dest.exists() || !dest.isDirectory) { "itch.io archive path collides with a directory: ${child.name}" }
|
||||
dest.parentFile?.mkdirs()
|
||||
move(child, dest)
|
||||
}
|
||||
if (Files.isSymbolicLink(destPath) || dest.exists()) {
|
||||
delete(dest)
|
||||
}
|
||||
Files.move(child.toPath(), destPath)
|
||||
}
|
||||
}
|
||||
|
||||
fun delete(file: File) = StoreInstallsSafeDelete.delete(file)
|
||||
|
||||
private fun safe(root: File, relative: String): File? {
|
||||
if (relative.isBlank() || relative.startsWith('/') || relative.contains('\\') || relative.split('/').any { it.isBlank() || it == "." || it == ".." }) return null
|
||||
val file = File(root, relative)
|
||||
var current = root
|
||||
for (segment in relative.split('/')) {
|
||||
current = File(current, segment)
|
||||
if (Files.isSymbolicLink(current.toPath())) return null
|
||||
}
|
||||
val canonical = file.canonicalFile
|
||||
return canonical.takeIf { it.path.startsWith(root.path + File.separator) }
|
||||
}
|
||||
|
||||
private fun validInventoryEntry(root: File, relative: String, value: String): Boolean =
|
||||
safe(root, relative.removeSuffix("/")) != null &&
|
||||
(if (value == DIRECTORY) relative.endsWith('/') else value.matches(HASH) && !relative.endsWith('/'))
|
||||
|
||||
private fun validateDone(root: File, done: JSONObject, allowed: Set<String>) {
|
||||
for (relative in done.keys()) {
|
||||
require(relative in allowed && safe(root, relative.removeSuffix("/")) != null && done.get(relative) is Boolean) {
|
||||
"The interrupted itch.io progress is invalid"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun readProgress(file: File, root: File, allowed: Set<String>): MutableSet<String> {
|
||||
require(!Files.isSymbolicLink(file.toPath())) { "The itch.io progress log is a symbolic link" }
|
||||
if (!file.exists()) return linkedSetOf()
|
||||
require(file.isFile) { "The itch.io progress log is not a regular file" }
|
||||
val bytes = file.readBytes()
|
||||
val text = bytes.toString(Charsets.UTF_8)
|
||||
val completed = linkedSetOf<String>()
|
||||
var start = 0
|
||||
while (true) {
|
||||
val end = text.indexOf('\n', start)
|
||||
if (end < 0) break
|
||||
val line = text.substring(start, end)
|
||||
require(line.isNotBlank()) { "The itch.io progress log contains an empty record" }
|
||||
val relative = runCatching { JSONObject(line).getString("path") }
|
||||
.getOrElse { throw IllegalStateException("The itch.io progress log is corrupt", it) }
|
||||
require(relative in allowed && safe(root, relative.removeSuffix("/")) != null) {
|
||||
"The itch.io progress log contains an invalid path"
|
||||
}
|
||||
completed += relative
|
||||
start = end + 1
|
||||
}
|
||||
val lastNewline = bytes.indexOfLast { it == '\n'.code.toByte() }
|
||||
if (lastNewline + 1 < bytes.size) {
|
||||
RandomAccessFile(file, "rw").use { journal ->
|
||||
journal.setLength((lastNewline + 1).toLong())
|
||||
journal.fd.sync()
|
||||
}
|
||||
}
|
||||
return completed
|
||||
}
|
||||
|
||||
private fun appendProgress(file: File, relative: String) {
|
||||
require(!Files.isSymbolicLink(file.toPath())) { "The itch.io progress log is a symbolic link" }
|
||||
val record = JSONObject().put("path", relative).toString() + "\n"
|
||||
FileOutputStream(file, true).use { output ->
|
||||
output.write(record.toByteArray(Charsets.UTF_8))
|
||||
output.fd.sync()
|
||||
}
|
||||
}
|
||||
|
||||
private fun sha256(file: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
FileInputStream(file).use { input ->
|
||||
val bytes = ByteArray(128 * 1024)
|
||||
while (true) { val n = input.read(bytes); if (n < 0) break; digest.update(bytes, 0, n) }
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
private fun move(from: File, to: File) {
|
||||
try { Files.move(from.toPath(), to.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
|
||||
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING) }
|
||||
}
|
||||
|
||||
private fun readJournal(file: File): JSONObject? {
|
||||
file.parentFile?.let { require(!Files.isSymbolicLink(it.toPath())) { "Maintenance metadata directory is a symbolic link" } }
|
||||
if (Files.isSymbolicLink(file.toPath())) throw IllegalStateException("The itch.io replacement journal is a symbolic link")
|
||||
if (!file.exists()) return null
|
||||
require(file.isFile) { "The itch.io replacement journal is not a regular file" }
|
||||
return runCatching { JSONObject(file.readText()) }.getOrElse { throw IllegalStateException("The itch.io replacement journal is corrupt", it) }
|
||||
}
|
||||
|
||||
private fun writeJournal(file: File, value: JSONObject) {
|
||||
val temp = File.createTempFile(".itch-commit-", ".tmp", file.parentFile)
|
||||
try {
|
||||
FileOutputStream(temp).use { it.write(value.toString().toByteArray(Charsets.UTF_8)); it.fd.sync() }
|
||||
move(temp, file)
|
||||
} finally { temp.delete() }
|
||||
}
|
||||
|
||||
private val HASH = Regex("[0-9a-f]{64}")
|
||||
}
|
||||
|
||||
private object StoreInstallsSafeDelete {
|
||||
fun delete(file: File) {
|
||||
if (!Files.isSymbolicLink(file.toPath()) && file.isDirectory) file.listFiles().orEmpty().forEach { delete(it) }
|
||||
if (!Files.isSymbolicLink(file.toPath()) && file.isDirectory) file.listFiles().orEmpty().forEach(::delete)
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
package com.droiddeck.launcher.stores.maintenance
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.StoreAccounts
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
enum class MaintenanceAction { UPDATE, REPAIR, REFRESH, OPEN_CLIENT }
|
||||
|
||||
enum class MaintenanceCheckState { UNKNOWN, CHECKING, CURRENT, AVAILABLE, FAILED }
|
||||
|
||||
data class MaintenanceCheck(
|
||||
val state: MaintenanceCheckState = MaintenanceCheckState.UNKNOWN,
|
||||
val version: String = "",
|
||||
val reason: String = "",
|
||||
)
|
||||
|
||||
enum class RecoveryState { NONE, RESUMABLE, NEEDS_ATTENTION }
|
||||
|
||||
data class MaintenanceRecovery(val state: RecoveryState = RecoveryState.NONE, val message: String = "")
|
||||
|
||||
data class MaintenanceProposal(
|
||||
val folder: File,
|
||||
val before: StoreGameSidecar,
|
||||
val targetLabel: String,
|
||||
val operation: MaintenanceAction,
|
||||
val downloadBytes: Long = UNKNOWN_BYTES,
|
||||
val diskBytes: Long = UNKNOWN_BYTES,
|
||||
val description: String = "",
|
||||
val target: JSONObject,
|
||||
) {
|
||||
companion object {
|
||||
const val UNKNOWN_BYTES = -1L
|
||||
}
|
||||
}
|
||||
|
||||
interface StoreMaintenanceAdapter {
|
||||
val store: Store
|
||||
fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction>
|
||||
fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck
|
||||
fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal
|
||||
fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean
|
||||
fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject)
|
||||
fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery = MaintenanceRecovery()
|
||||
fun openClient(context: Context, game: InstalledStoreGame) = Unit
|
||||
fun openClientLabel(game: InstalledStoreGame): String = "Open client"
|
||||
}
|
||||
|
||||
object StoreMaintenance {
|
||||
const val OPERATION_KEY = "maintenanceOperation"
|
||||
const val FOLDER_KEY = "maintenanceFolder"
|
||||
private const val JOURNAL = "operation.json"
|
||||
private const val CHECK_INTERVAL_MS = 30 * 60_000L
|
||||
private val adapters = ConcurrentHashMap<Store, StoreMaintenanceAdapter>()
|
||||
private val workers = Executors.newFixedThreadPool(2)
|
||||
private val checkedAt = ConcurrentHashMap<String, Long>()
|
||||
private val inFlight = ConcurrentHashMap<String, Long>()
|
||||
private val revisions = ConcurrentHashMap<Store, Long>()
|
||||
private val accounts = ConcurrentHashMap<Store, String>()
|
||||
private val operationLocks = ConcurrentHashMap<String, Any>()
|
||||
private val preparing = ConcurrentHashMap.newKeySet<String>()
|
||||
val checks = mutableStateMapOf<String, MaintenanceCheck>()
|
||||
|
||||
fun register(adapter: StoreMaintenanceAdapter) {
|
||||
adapters[adapter.store] = adapter
|
||||
}
|
||||
|
||||
fun adapter(store: Store): StoreMaintenanceAdapter? = adapters[store]
|
||||
|
||||
fun adapter(game: InstalledStoreGame): StoreMaintenanceAdapter? = adapter(game.sidecar.store)
|
||||
|
||||
fun check(game: InstalledStoreGame): MaintenanceCheck = checks[game.key] ?: MaintenanceCheck()
|
||||
|
||||
fun checkInstalled(context: Context, games: List<InstalledStoreGame>) {
|
||||
games.forEach { game -> if (game.sidecar.isInstalled && adapters.containsKey(game.sidecar.store)) check(context, game) }
|
||||
}
|
||||
|
||||
fun check(context: Context, game: InstalledStoreGame, force: Boolean = false) {
|
||||
val adapter = adapters[game.sidecar.store] ?: return
|
||||
val account = StoreAccounts.displayName(context, game.sidecar.store).orEmpty()
|
||||
val previous = accounts.put(game.sidecar.store, account)
|
||||
if (previous != null && previous != account) invalidate(game.sidecar.store)
|
||||
val key = "${game.sidecar.store.id}:${game.folder.canonicalPath}"
|
||||
if (!force && System.currentTimeMillis() - (checkedAt[key] ?: 0L) < CHECK_INTERVAL_MS) return
|
||||
val owner = revisions[game.sidecar.store] ?: 0L
|
||||
if (inFlight.putIfAbsent(key, owner) != null) return
|
||||
StoresState.post { if ((revisions[game.sidecar.store] ?: 0L) == owner) checks[game.key] = MaintenanceCheck(MaintenanceCheckState.CHECKING) }
|
||||
workers.execute {
|
||||
try {
|
||||
val result = runCatching { adapter.check(context.applicationContext, game) }
|
||||
.getOrElse { MaintenanceCheck(MaintenanceCheckState.FAILED, reason = it.message ?: "${game.sidecar.store.label} update check failed") }
|
||||
if ((revisions[game.sidecar.store] ?: 0L) == owner && (result.state == MaintenanceCheckState.CURRENT || result.state == MaintenanceCheckState.AVAILABLE))
|
||||
checkedAt[key] = System.currentTimeMillis()
|
||||
StoresState.post { if ((revisions[game.sidecar.store] ?: 0L) == owner) checks[game.key] = result }
|
||||
} finally { inFlight.remove(key, owner) }
|
||||
}
|
||||
}
|
||||
|
||||
fun invalidate(store: Store) {
|
||||
revisions.compute(store) { _, revision -> (revision ?: 0L) + 1L }
|
||||
checkedAt.keys.removeIf { it.startsWith("${store.id}:") }
|
||||
inFlight.keys.removeIf { it.startsWith("${store.id}:") }
|
||||
StoresState.post { checks.keys.removeIf { it.startsWith("${store.id}:") } }
|
||||
}
|
||||
|
||||
fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal {
|
||||
require(action in capabilities(game)) { "${game.sidecar.store.label} does not support ${action.name.lowercase()}" }
|
||||
require(action != MaintenanceAction.OPEN_CLIENT)
|
||||
val adapter = adapters[game.sidecar.store] ?: error("${game.sidecar.store.label} maintenance is unavailable")
|
||||
val folder = game.folder.canonicalFile
|
||||
synchronized(operationLock(folder)) {
|
||||
requireCurrentInstalledGame(game)
|
||||
check(preparing.add(folder.path)) { "${game.sidecar.store.label} maintenance is already being prepared" }
|
||||
}
|
||||
return try {
|
||||
adapter.prepare(context.applicationContext, game, action)
|
||||
} finally {
|
||||
synchronized(operationLock(folder)) { preparing.remove(folder.path) }
|
||||
}
|
||||
}
|
||||
|
||||
fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> =
|
||||
adapters[game.sidecar.store]?.capabilities(game).orEmpty()
|
||||
|
||||
fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal) {
|
||||
require(game.folder.canonicalFile == proposal.folder.canonicalFile)
|
||||
require(proposal.operation != MaintenanceAction.OPEN_CLIENT && proposal.operation in capabilities(game))
|
||||
val adapter = adapters[game.sidecar.store] ?: error("${game.sidecar.store.label} maintenance is unavailable")
|
||||
val folder = game.folder.canonicalFile
|
||||
synchronized(operationLock(folder)) {
|
||||
requireCurrentInstalledGame(game)
|
||||
check(folder.path !in preparing) { "${game.sidecar.store.label} maintenance is being prepared" }
|
||||
require(!com.droiddeck.launcher.stores.download.DownloadQueue.isActive(game.key)) {
|
||||
"${game.sidecar.store.label} already has an active operation"
|
||||
}
|
||||
val enqueueId = java.util.UUID.randomUUID().toString()
|
||||
writeOperation(proposal, game, enqueueId)
|
||||
val accepted = try {
|
||||
adapter.enqueue(context.applicationContext, game, proposal)
|
||||
} catch (error: Throwable) {
|
||||
runCatching { clearNewQueuedOperation(game, enqueueId, preserveActive = true) }
|
||||
.onFailure(error::addSuppressed)
|
||||
throw error
|
||||
}
|
||||
if (!accepted) {
|
||||
clearNewQueuedOperation(game, enqueueId, preserveActive = false)
|
||||
error("${game.sidecar.store.label} already has an active operation")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun beginUninstall(game: InstalledStoreGame): Boolean {
|
||||
val folder = game.folder.canonicalFile
|
||||
return synchronized(operationLock(folder)) {
|
||||
if (game.key in StoresState.uninstalling || folder.path in preparing) return@synchronized false
|
||||
val hasSharedApply = capabilities(game).any { it != MaintenanceAction.OPEN_CLIENT }
|
||||
val currentInstall = runCatching {
|
||||
if (hasSharedApply) requireCurrentInstalledGame(game)
|
||||
else require(folder.isDirectory && !Files.isSymbolicLink(folder.toPath()))
|
||||
readOperation(folder) == null
|
||||
}.getOrDefault(false)
|
||||
if (!currentInstall) return@synchronized false
|
||||
StoresState.uninstalling[game.key] = 0f
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fun resume(context: Context, game: InstalledStoreGame) {
|
||||
requireInstalledFolder(context, game.folder)
|
||||
val adapter = adapters[game.sidecar.store] ?: error("${game.sidecar.store.label} maintenance is unavailable")
|
||||
val operation = readOperation(game.folder) ?: error("${game.sidecar.store.label} operation journal is missing")
|
||||
require(operation.optString("folder") == game.folder.canonicalPath && operation.optString("store") == game.sidecar.store.id && operation.optString("id") == game.sidecar.id)
|
||||
adapter.resume(context.applicationContext, game, operation)
|
||||
}
|
||||
|
||||
fun openClient(context: Context, game: InstalledStoreGame) {
|
||||
require(MaintenanceAction.OPEN_CLIENT in capabilities(game))
|
||||
adapters[game.sidecar.store]?.openClient(context.applicationContext, game)
|
||||
}
|
||||
|
||||
fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
|
||||
val adapterRecovery = try { adapters[game.sidecar.store]?.recovery(context.applicationContext, game) }
|
||||
catch (error: Exception) { return MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, error.message ?: "The maintenance journal could not be read") }
|
||||
if (adapterRecovery?.state != null && adapterRecovery.state != RecoveryState.NONE) return adapterRecovery
|
||||
val operation = try { readOperation(game.folder) }
|
||||
catch (error: Exception) { return MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, error.message ?: "The maintenance journal could not be read") }
|
||||
if (operation != null) {
|
||||
val state = if (operation.optString("phase") in setOf("queued", "download")) RecoveryState.RESUMABLE else RecoveryState.NEEDS_ATTENTION
|
||||
return MaintenanceRecovery(state, operation.optString("phase"))
|
||||
}
|
||||
if (!game.sidecar.isInstalled) return MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, "The installation did not finish")
|
||||
return adapterRecovery ?: MaintenanceRecovery()
|
||||
}
|
||||
|
||||
fun operationFile(folder: File) = File(File(folder, ".droiddeck-maintenance"), JOURNAL)
|
||||
|
||||
fun readOperation(folder: File): JSONObject? {
|
||||
val directory = File(folder, ".droiddeck-maintenance")
|
||||
val file = File(directory, JOURNAL)
|
||||
require(!Files.isSymbolicLink(directory.toPath()) && !Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
|
||||
return file.takeIf { it.isFile }?.let {
|
||||
JSONObject(it.readText()).also { operation ->
|
||||
require(operation.optInt("schema") == 1) { "Unsupported store maintenance journal" }
|
||||
require(operation.optString("folder") == folder.canonicalPath) { "Maintenance journal folder does not match" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clearOperation(folder: File) {
|
||||
val directory = File(folder, ".droiddeck-maintenance")
|
||||
val file = File(directory, JOURNAL)
|
||||
require(!Files.isSymbolicLink(directory.toPath()) && !Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
|
||||
if (!file.exists()) return
|
||||
require(file.isFile) { "Maintenance journal is not a regular file" }
|
||||
val operation = readOperation(folder) ?: return
|
||||
require(operation.optString("phase") in setOf("queued", "download")) { "An applying maintenance operation must be recovered" }
|
||||
require(!Files.isSymbolicLink(directory.toPath()) && !Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
|
||||
check(file.delete()) { "Could not clear the queued maintenance operation" }
|
||||
}
|
||||
|
||||
fun <T> withApplyLease(game: InstalledStoreGame, block: () -> T): T {
|
||||
return beginApplyLease(game).use { block() }
|
||||
}
|
||||
|
||||
fun beginApplyLease(game: InstalledStoreGame): AutoCloseable {
|
||||
val folder = game.folder.canonicalFile
|
||||
synchronized(operationLock(folder)) { return beginApplyLeaseLocked(game, folder) }
|
||||
}
|
||||
|
||||
private fun beginApplyLeaseLocked(game: InstalledStoreGame, folder: File): AutoCloseable {
|
||||
require(folder == game.folder.absoluteFile.canonicalFile)
|
||||
val operation = readOperation(folder) ?: error("${game.sidecar.store.label} operation journal is missing")
|
||||
require(operation.optString("folder") == folder.path && operation.optString("store") == game.sidecar.store.id && operation.optString("id") == game.sidecar.id)
|
||||
val directory = File(folder, ".droiddeck-maintenance")
|
||||
require(!Files.isSymbolicLink(directory.toPath())) { "Maintenance metadata directory is a symbolic link" }
|
||||
directory.mkdirs()
|
||||
val leaseFile = File(directory, "lease")
|
||||
require(!Files.isSymbolicLink(leaseFile.toPath())) { "Maintenance lease is a symbolic link" }
|
||||
val lease = RandomAccessFile(leaseFile, "rw")
|
||||
val lock = runCatching { lease.channel.tryLock() }.getOrNull() ?: run {
|
||||
lease.close()
|
||||
error("Close the game before maintenance")
|
||||
}
|
||||
try {
|
||||
val before = StoreGameSidecar.parse(operation.getJSONObject("before").toString())
|
||||
?: error("The original ${game.sidecar.store.label} settings are missing")
|
||||
require(before.store == game.sidecar.store && before.id == game.sidecar.id)
|
||||
writeJson(operationFile(folder), operation.put("phase", "applying"))
|
||||
before.copy(state = StoreGameSidecar.STATE_UPDATING).write(folder)
|
||||
} catch (error: Throwable) {
|
||||
lock.close()
|
||||
lease.close()
|
||||
throw error
|
||||
}
|
||||
return AutoCloseable { lock.close(); lease.close() }
|
||||
}
|
||||
|
||||
private fun operationLock(folder: File): Any = operationLocks.computeIfAbsent(folder.path) { Any() }
|
||||
|
||||
private fun requireCurrentInstalledGame(game: InstalledStoreGame) {
|
||||
val folder = game.folder.canonicalFile
|
||||
require(game.sidecar.isInstalled && folder.isDirectory && !Files.isSymbolicLink(folder.toPath())) {
|
||||
"${game.sidecar.store.label} installation is no longer available"
|
||||
}
|
||||
val current = StoreGameSidecar.read(folder)
|
||||
require(current?.store == game.sidecar.store && current.id == game.sidecar.id && current.isInstalled) {
|
||||
"${game.sidecar.store.label} installation record is no longer available"
|
||||
}
|
||||
require(game.key !in StoresState.uninstalling) { "${game.sidecar.store.label} game is being uninstalled" }
|
||||
}
|
||||
|
||||
private fun clearNewQueuedOperation(game: InstalledStoreGame, enqueueId: String, preserveActive: Boolean) {
|
||||
val folder = game.folder.canonicalFile
|
||||
if (preserveActive && com.droiddeck.launcher.stores.download.DownloadQueue.isActive(game.key)) return
|
||||
val operation = readOperation(folder) ?: return
|
||||
if (operation.optString("enqueueId") != enqueueId || operation.optString("phase") != "queued" ||
|
||||
operation.optString("folder") != folder.path || operation.optString("store") != game.sidecar.store.id ||
|
||||
operation.optString("id") != game.sidecar.id) return
|
||||
val file = operationFile(folder)
|
||||
require(!Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
|
||||
if (file.isFile) check(file.delete()) { "Could not clear the failed queued maintenance operation" }
|
||||
}
|
||||
|
||||
fun complete(
|
||||
context: Context,
|
||||
game: InstalledStoreGame,
|
||||
installVersion: String = game.sidecar.installVersion,
|
||||
updatedExtra: Map<String, String>? = null,
|
||||
) {
|
||||
val folder = game.folder.canonicalFile
|
||||
val operation = readOperation(folder) ?: error("${game.sidecar.store.label} operation journal is missing")
|
||||
require(operation.optString("folder") == folder.path && operation.optString("store") == game.sidecar.store.id && operation.optString("id") == game.sidecar.id)
|
||||
require(operation.optString("phase") == "applying") { "The ${game.sidecar.store.label} operation was not applied" }
|
||||
val before = StoreGameSidecar.parse(operation.getJSONObject("before").toString())
|
||||
?: error("The original ${game.sidecar.store.label} settings are missing")
|
||||
StoreInstalls.complete(context.applicationContext, folder,
|
||||
before.copy(installVersion = installVersion, extra = updatedExtra ?: before.extra, state = StoreGameSidecar.STATE_INSTALLED))
|
||||
check(operationFile(folder).delete()) { "Could not finish the ${game.sidecar.store.label} recovery record" }
|
||||
checkedAt.remove("${game.sidecar.store.id}:${folder.path}")
|
||||
StoresState.post { checks.remove(game.key) }
|
||||
}
|
||||
|
||||
private fun writeOperation(proposal: MaintenanceProposal, game: InstalledStoreGame, enqueueId: String) {
|
||||
val folder = proposal.folder.canonicalFile
|
||||
require(proposal.before.store == game.sidecar.store && proposal.before.id == game.sidecar.id)
|
||||
val directory = File(folder, ".droiddeck-maintenance")
|
||||
require(!Files.isSymbolicLink(directory.toPath())) { "Maintenance metadata directory is a symbolic link" }
|
||||
directory.mkdirs()
|
||||
val file = File(directory, JOURNAL)
|
||||
require(!Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
|
||||
require(!file.exists()) { "Resume or recover the existing ${game.sidecar.store.label} operation first" }
|
||||
val value = JSONObject().put("schema", 1).put("store", game.sidecar.store.id).put("id", game.sidecar.id)
|
||||
.put("folder", folder.path).put("enqueueId", enqueueId).put("operation", proposal.operation.name).put("phase", "queued")
|
||||
.put("before", proposal.before.toJson()).put("targetLabel", proposal.targetLabel)
|
||||
.put("downloadBytes", proposal.downloadBytes).put("diskBytes", proposal.diskBytes)
|
||||
.put("description", proposal.description).put("target", proposal.target)
|
||||
writeJson(file, value)
|
||||
}
|
||||
|
||||
private fun writeJson(file: File, value: JSONObject) {
|
||||
require(!Files.isSymbolicLink(file.toPath())) { "Maintenance journal is a symbolic link" }
|
||||
file.parentFile?.mkdirs()
|
||||
val temp = File.createTempFile(".maintenance-", ".tmp", file.parentFile)
|
||||
try {
|
||||
FileOutputStream(temp).use { it.write(value.toString().toByteArray(Charsets.UTF_8)); it.fd.sync() }
|
||||
try { Files.move(temp.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
|
||||
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING) }
|
||||
} finally { temp.delete() }
|
||||
}
|
||||
|
||||
fun restore(context: Context, item: CatalogItem) {
|
||||
if (item.store == Store.GOG && item.extra.containsKey("gogOperation")) {
|
||||
com.droiddeck.launcher.stores.gog.GogMaintenance.restore(context, item)
|
||||
return
|
||||
}
|
||||
if (adapters[item.store] == null) error("${item.store.label} maintenance is unavailable")
|
||||
val folder = item.extra["maintenanceFolder"] ?: item.extra["gogFolder"]
|
||||
?: error("Missing ${item.store.label} recovery folder")
|
||||
requireInstalledFolder(context, File(folder))
|
||||
val installed = InstalledStoreGame(
|
||||
StoreGameSidecar.read(File(folder)) ?: error("${item.store.label} installation record is missing"),
|
||||
File(folder),
|
||||
)
|
||||
require(installed.sidecar.store == item.store && installed.sidecar.id == item.id)
|
||||
resume(context, installed)
|
||||
}
|
||||
|
||||
private fun requireInstalledFolder(context: Context, folder: File) {
|
||||
val canonical = folder.canonicalFile
|
||||
require(StoreInstallRoot.gameFolders(context.applicationContext).any { it.canonicalFile == canonical }) {
|
||||
"Maintenance folder is outside the installed game roots"
|
||||
}
|
||||
}
|
||||
|
||||
fun launchExcluded(game: InstalledStoreGame): Boolean {
|
||||
if (!game.sidecar.isInstalled) return true
|
||||
val gogJournal = if (game.sidecar.store == Store.GOG) File(game.folder, ".droiddeck-gog/operation.json") else null
|
||||
if (gogJournal?.isFile == true) {
|
||||
val phase = runCatching { JSONObject(gogJournal.readText()).optString("phase") }.getOrDefault("")
|
||||
if (phase != "download") return true
|
||||
}
|
||||
val queued = com.droiddeck.launcher.stores.download.DownloadQueue.isActive(game.key)
|
||||
val file = operationFile(game.folder)
|
||||
val journal = file.exists() && !runCatching { readOperation(game.folder)?.optString("phase") in setOf("queued", "download") }.getOrDefault(false)
|
||||
return queued || journal
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,18 @@ import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.stores.*
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
object XboxBackend : StoreBackend {
|
||||
override val store = Store.XBOX
|
||||
override fun maintenanceAdapter(): StoreMaintenanceAdapter = XboxMaintenanceAdapter
|
||||
@Volatile private var access: Map<String, String> = emptyMap()
|
||||
@Volatile private var generation = 0
|
||||
private var syncing: Int? = null
|
||||
@@ -148,6 +156,55 @@ object XboxBackend : StoreBackend {
|
||||
enqueue(context, item, root)
|
||||
}
|
||||
|
||||
internal fun maintenanceCheck(context: Context, game: InstalledStoreGame): MaintenanceCheck {
|
||||
return try {
|
||||
if (StoreAccounts.signedInAs(context, store) == null)
|
||||
return MaintenanceCheck(MaintenanceCheckState.FAILED, reason = "Sign in to Xbox before checking package updates")
|
||||
val contentId = game.sidecar.extra["contentId"].orEmpty()
|
||||
if (!contentId.matches(Regex("[a-fA-F0-9-]{36}")))
|
||||
return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "The installed Xbox package identity is unknown")
|
||||
val market = game.sidecar.extra["market"]?.takeIf { it.matches(Regex("[A-Z]{2}")) } ?: Xodus.market()
|
||||
val plan = Xodus.run(context.applicationContext, listOf("resolve-package", game.sidecar.id, "--json", "--market", market))
|
||||
if (plan.optString("status") != "ready")
|
||||
return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Xodus did not resolve a current Xbox package")
|
||||
val choice = XboxCatalog.objects(plan.optJSONArray("choices")).firstOrNull { it.optString("contentId").equals(contentId, true) }
|
||||
?: return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "The installed Xbox package is not in the current package choices")
|
||||
val version = listOf("version", "packageVersion", "package_version").firstNotNullOfOrNull { key -> choice.optString(key).takeIf { it.isNotBlank() } }
|
||||
?: return MaintenanceCheck(MaintenanceCheckState.UNKNOWN, reason = "Xodus did not expose a current package version")
|
||||
val installed = runCatching { XboxManifest.read(game.folder).version }.getOrDefault(game.sidecar.installVersion)
|
||||
if (installed.isBlank()) MaintenanceCheck(MaintenanceCheckState.UNKNOWN, version, "The installed Xbox package version is unknown")
|
||||
else MaintenanceCheck(if (installed == version) MaintenanceCheckState.CURRENT else MaintenanceCheckState.AVAILABLE, version)
|
||||
} catch (error: Exception) {
|
||||
MaintenanceCheck(MaintenanceCheckState.FAILED, reason = error.message ?: "Xbox package check failed")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun prepareMaintenance(context: Context, game: InstalledStoreGame): MaintenanceProposal {
|
||||
check(!XboxRuntime.isActive(game.sidecar.id)) { "Close this Xbox game before updating it." }
|
||||
val contentId = game.sidecar.extra["contentId"].orEmpty()
|
||||
require(contentId.matches(Regex("[a-fA-F0-9-]{36}"))) { "The installed Xbox package identity is unknown." }
|
||||
val market = game.sidecar.extra["market"]?.takeIf { it.matches(Regex("[A-Z]{2}")) } ?: Xodus.market()
|
||||
val version = maintenanceCheck(context, game).takeIf { it.state == MaintenanceCheckState.AVAILABLE }?.version.orEmpty()
|
||||
val size = MaintenanceProposal.UNKNOWN_BYTES
|
||||
val target = JSONObject().put("schema", 1).put("contentId", contentId).put("market", market).put("version", version)
|
||||
return MaintenanceProposal(game.folder.canonicalFile, game.sidecar, version.ifBlank { "latest licensed Xbox package" }, MaintenanceAction.UPDATE,
|
||||
downloadBytes = size, diskBytes = size, description = "Xodus refreshes the installed package through its licensed streaming path.", target = target)
|
||||
}
|
||||
|
||||
internal fun enqueueMaintenance(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean {
|
||||
val sidecar = game.sidecar
|
||||
val item = CatalogItem(store, sidecar.id, sidecar.title, sidecar.hero, tallImageUrl = sidecar.cover,
|
||||
owned = sidecar.extra["access"] == "owned", subscription = sidecar.extra["access"] == "gamepass",
|
||||
extra = sidecar.extra + mapOf("contentId" to proposal.target.getString("contentId"), "market" to proposal.target.getString("market"),
|
||||
StoreMaintenance.OPERATION_KEY to MaintenanceAction.UPDATE.name, StoreMaintenance.FOLDER_KEY to game.folder.canonicalPath))
|
||||
val root = game.folder.parentFile?.parentFile ?: error("Xbox install root is missing")
|
||||
val entry = DownloadEntry(store, sidecar.id, sidecar.title, cover = sidecar.cover,
|
||||
bytesTotal = proposal.downloadBytes, location = StoreInstallRoot.labelFor(context, game.folder))
|
||||
return DownloadQueue.enqueueIfIdle(context.applicationContext, entry, onAccepted = {
|
||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(context, item, root)
|
||||
}) { XboxInstaller(context.applicationContext, item, game.folder, game) }
|
||||
}
|
||||
|
||||
private fun enqueue(context: Context, item: CatalogItem, root: File) {
|
||||
val app = context.applicationContext
|
||||
val folder = StoreInstallRoot.folderFor(app, store, item.id, item.title, root)
|
||||
|
||||
@@ -4,13 +4,15 @@ import android.content.Context
|
||||
import com.droiddeck.launcher.stores.*
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal class XboxInstaller(private val app: Context, private val item: CatalogItem, private val folder: File) : DownloadQueue.DownloadJob {
|
||||
internal class XboxInstaller(private val app: Context, private val item: CatalogItem, private val folder: File,
|
||||
private val maintenanceGame: InstalledStoreGame? = null) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
private val paused = CountDownLatch(1)
|
||||
@Volatile private var child: Xodus.Child? = null
|
||||
@@ -32,8 +34,10 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
folder.mkdirs()
|
||||
} else {
|
||||
check(!XboxRuntime.isActive(item.id)) { "Close this Xbox game before updating it." }
|
||||
StoreInstalls.markUpdating(folder)
|
||||
StoreInstalls.begin(folder, Store.XBOX, item.id, item.title, item.tallImageUrl, item.imageUrl)
|
||||
if (maintenanceGame == null) {
|
||||
StoreInstalls.markUpdating(folder)
|
||||
StoreInstalls.begin(folder, Store.XBOX, item.id, item.title, item.tallImageUrl, item.imageUrl)
|
||||
}
|
||||
}
|
||||
var complete = false
|
||||
var sequence = -1L
|
||||
@@ -41,8 +45,9 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
val source = if (content) selected else item.id
|
||||
val guestFolder = StoreInstallRoot.guestPathForXodus(app, folder)
|
||||
val selection = if (content) emptyList() else listOf("--selected-content-id", selected)
|
||||
Xodus.start(app, listOf("streaming", source, guestFolder, "--market", market,
|
||||
"--progress-json", "--control-stdin") + selection).use { process ->
|
||||
val stream = stream@ {
|
||||
Xodus.start(app, listOf("streaming", source, guestFolder, "--market", market,
|
||||
"--progress-json", "--control-stdin") + selection).use { process ->
|
||||
child = process
|
||||
val rejected = AtomicBoolean(false)
|
||||
val rejectedLine = Regex(Xodus.SIGN_IN_REJECTED)
|
||||
@@ -67,18 +72,25 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
} }
|
||||
check(process.process.waitFor(15, TimeUnit.SECONDS)) { "Xbox installer did not exit." }
|
||||
diagnostics.join(2000)
|
||||
if (cancelled.get()) return null
|
||||
if (cancelled.get()) return@stream
|
||||
check(!rejected.get()) { app.getString(com.droiddeck.launcher.R.string.stores_xbox_sign_in_again) }
|
||||
check(process.process.exitValue() == 0 && complete) { "Xbox download did not complete. Resume to retry with fresh licenses." }
|
||||
}
|
||||
}
|
||||
if (maintenanceGame != null) StoreMaintenance.withApplyLease(maintenanceGame, stream) else stream()
|
||||
if (cancelled.get()) return null
|
||||
if (content) {
|
||||
XboxContent.complete(app, item, folder)
|
||||
return folder.path
|
||||
}
|
||||
val exe = executable(folder)
|
||||
StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe,
|
||||
installVersion = XboxManifest.read(folder).version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl,
|
||||
extra = item.extra + mapOf("contentId" to selected, "market" to market)))
|
||||
val version = XboxManifest.read(folder).version
|
||||
if (maintenanceGame != null) {
|
||||
StoreMaintenance.complete(app, maintenanceGame, version,
|
||||
maintenanceSidecarExtra(maintenanceGame.sidecar.extra, selected, market))
|
||||
} else StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe,
|
||||
installVersion = version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl,
|
||||
extra = maintenanceSidecarExtra(item.extra, selected, market)))
|
||||
return folder.path
|
||||
} finally {
|
||||
child = null
|
||||
@@ -89,11 +101,11 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
delete = deleteFiles
|
||||
delete = deleteFiles && maintenanceGame == null
|
||||
val process = child
|
||||
if (process == null) {
|
||||
if (deleteFiles && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteTree(folder)
|
||||
else if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
|
||||
if (delete && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteTree(folder)
|
||||
else if (delete) StoreInstalls.discard(app, folder, emptyList())
|
||||
return
|
||||
}
|
||||
Thread({
|
||||
@@ -107,5 +119,13 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
|
||||
companion object {
|
||||
internal fun executable(folder: File): String = XboxManifest.executable(folder)
|
||||
|
||||
internal fun maintenanceSidecarExtra(before: Map<String, String>, contentId: String, market: String): Map<String, String> =
|
||||
LinkedHashMap(before).apply {
|
||||
remove(StoreMaintenance.OPERATION_KEY)
|
||||
remove(StoreMaintenance.FOLDER_KEY)
|
||||
put("contentId", contentId)
|
||||
put("market", market)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheck
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
|
||||
import com.droiddeck.launcher.stores.maintenance.RecoveryState
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenanceAdapter
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
internal object XboxMaintenanceAdapter : StoreMaintenanceAdapter {
|
||||
override val store = Store.XBOX
|
||||
|
||||
override fun capabilities(game: InstalledStoreGame): Set<MaintenanceAction> =
|
||||
if (game.sidecar.extra["contentId"].orEmpty().matches(Regex("[a-fA-F0-9-]{36}"))) setOf(MaintenanceAction.UPDATE) else emptySet()
|
||||
|
||||
override fun check(context: Context, game: InstalledStoreGame): MaintenanceCheck = XboxBackend.maintenanceCheck(context, game)
|
||||
|
||||
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal {
|
||||
require(action == MaintenanceAction.UPDATE) { "Xbox Repair is not exposed by Xodus" }
|
||||
return XboxBackend.prepareMaintenance(context, game)
|
||||
}
|
||||
|
||||
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean {
|
||||
require(proposal.operation == MaintenanceAction.UPDATE && proposal.target.optInt("schema") == 1)
|
||||
return XboxBackend.enqueueMaintenance(context, game, proposal)
|
||||
}
|
||||
|
||||
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) {
|
||||
require(operation.optString("phase") in setOf("queued", "download", "applying"))
|
||||
val target = operation.optJSONObject("target") ?: error("Xbox maintenance target is missing")
|
||||
require(target.optInt("schema") == 1 && target.optString("contentId").matches(Regex("[a-fA-F0-9-]{36}")))
|
||||
val proposal = MaintenanceProposal(game.folder.canonicalFile,
|
||||
com.droiddeck.launcher.stores.StoreGameSidecar.parse(operation.getJSONObject("before").toString())
|
||||
?: error("The original Xbox settings are missing"), operation.optString("targetLabel"), MaintenanceAction.UPDATE,
|
||||
operation.optLong("downloadBytes", MaintenanceProposal.UNKNOWN_BYTES),
|
||||
operation.optLong("diskBytes", MaintenanceProposal.UNKNOWN_BYTES), operation.optString("description"), JSONObject(target.toString()))
|
||||
check(XboxBackend.enqueueMaintenance(context, game, proposal)) { "Xbox maintenance is already queued" }
|
||||
}
|
||||
|
||||
override fun recovery(context: Context, game: InstalledStoreGame): MaintenanceRecovery {
|
||||
val journal = StoreMaintenance.readOperation(game.folder) ?: return MaintenanceRecovery()
|
||||
return when (journal.optString("phase")) {
|
||||
"queued", "download", "applying" -> MaintenanceRecovery(RecoveryState.RESUMABLE, "Resume the Xodus package update")
|
||||
else -> MaintenanceRecovery(RecoveryState.NEEDS_ATTENTION, "The Xbox package update needs recovery")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -258,7 +258,7 @@ class FrontEndActions(
|
||||
val onCopyPhantomCommand: (Boolean) -> Unit = {},
|
||||
val onDismissPhantomGate: () -> Unit = {},
|
||||
val onStartWirelessAdbPairing: () -> Unit = {},
|
||||
val onStartPairingGuide: (Int?) -> Boolean = { false },
|
||||
val onStartPairingGuide: (Int?, Boolean) -> Boolean = { _, _ -> false },
|
||||
val onShowPhantomGate: () -> Unit = {},
|
||||
val onOpenNotificationSettings: () -> Unit = {},
|
||||
val controller: ControllerActions? = null,
|
||||
@@ -431,6 +431,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
|
||||
var developerChoiceGuided by rememberSaveable { mutableStateOf(false) }
|
||||
var developerChoiceToggle by rememberSaveable { mutableStateOf(false) }
|
||||
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -440,13 +441,26 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
|
||||
val requestDeveloperOptions = {
|
||||
developerChoiceGuided = false
|
||||
developerChoiceToggle = false
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
val openDeveloperOptionsOn: (Int?) -> Unit = { displayId ->
|
||||
if (developerChoiceGuided) a.onStartWirelessAdbPairing()
|
||||
if (!developerChoiceGuided || !a.onStartPairingGuide(displayId)) a.onOpenDeveloperOptions(displayId)
|
||||
val guided = developerChoiceGuided || developerChoiceToggle
|
||||
if (!guided || !a.onStartPairingGuide(displayId, developerChoiceToggle)) a.onOpenDeveloperOptions(displayId)
|
||||
developerChoiceGuided = false
|
||||
developerChoiceToggle = false
|
||||
}
|
||||
val requestChildProcessToggle = {
|
||||
if (!PhantomProcessLimit.hasDeveloperToggle() || com.droiddeck.launcher.core.GlobalSettings.developerOptionsOn(ctx)) {
|
||||
requestDeveloperOptions()
|
||||
} else {
|
||||
developerChoiceGuided = false
|
||||
developerChoiceToggle = true
|
||||
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
}
|
||||
val startGuidedPairing = {
|
||||
if (!com.droiddeck.launcher.core.WirelessAdbPairingService.notificationsEnabled(ctx)) {
|
||||
@@ -627,7 +641,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
},
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
onOpenDeveloperOptions = requestChildProcessToggle,
|
||||
onRequestWirelessAdb = requestWirelessAdbFix,
|
||||
onPairWirelessDebugging = startGuidedPairing,
|
||||
)
|
||||
@@ -662,7 +676,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
PhantomProcessGatePage(
|
||||
status = s.phantomProcessStatus,
|
||||
onDismiss = a.onDismissPhantomGate,
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
onOpenDeveloperOptions = requestChildProcessToggle,
|
||||
applyingSavedPairing = applyingSavedPairing,
|
||||
onFixWithWirelessDebugging = fixPhantomLimit,
|
||||
onEnterAddressManually = { requestWirelessAdbFix(false) },
|
||||
@@ -699,6 +713,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
onDismiss = {
|
||||
showDeveloperDisplayChoice = false
|
||||
developerChoiceGuided = false
|
||||
developerChoiceToggle = false
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -90,6 +90,7 @@ import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.xbox.XboxBackend
|
||||
import com.droiddeck.launcher.stores.xbox.XboxCloudGames
|
||||
@@ -351,7 +352,7 @@ internal fun GameActions(
|
||||
val gone = storeKey?.let { StoresState.uninstalling[it] }
|
||||
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
|
||||
PrimaryButton(
|
||||
stringResource(R.string.stores_play), enabled = !s.busy && gone == null && download == null && !xboxBusy,
|
||||
stringResource(R.string.stores_play), enabled = !s.busy && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
|
||||
main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn,
|
||||
) {
|
||||
if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(ctx, store, id, s, a)
|
||||
@@ -362,26 +363,19 @@ internal fun GameActions(
|
||||
GameShortcutMenu(game, a)
|
||||
EditArtButton(game)
|
||||
}
|
||||
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.ITCH && installed != null && StoreMaintenance.adapter(installed) == null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
|
||||
if (store != Store.GOG && installed != null && installed.key !in StoresState.uninstalling && StoreMaintenance.adapter(installed) != null) StoreMaintenanceActions(installed)
|
||||
if (store == null && game != null && game.source == Library.SOURCE_STEAM && game.appId > 0) SteamClientMaintenanceActions(a, s.sessionRunning)
|
||||
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
|
||||
if (store == Store.XBOX && installed != null && id != null) {
|
||||
SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
|
||||
if (StoreMaintenance.adapter(installed) == null) SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
|
||||
runCatching { XboxBackend.update(ctx, installed) }
|
||||
.onFailure { StoresState.problems[Store.XBOX] = it.message ?: ctx.getString(R.string.stores_xbox_close_first) }
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
|
||||
}
|
||||
if (store == Store.BATTLENET) {
|
||||
if (installed != null && id != null) {
|
||||
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
|
||||
if (download != null) {
|
||||
ActionChip(downloadLabel(download), ok = false)
|
||||
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
|
||||
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
|
||||
} else if (BattleNetInstall.updates[id] == true) {
|
||||
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
|
||||
}
|
||||
}
|
||||
if (store == Store.BATTLENET && installed == null) {
|
||||
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import com.droiddeck.launcher.stores.gog.*
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@Composable
|
||||
internal fun GogMaintenanceActions(game: InstalledStoreGame) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val scope = rememberCoroutineScope()
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var patches by remember { mutableStateOf<List<GogOfflineDownload>?>(null) }
|
||||
var proposal by remember { mutableStateOf<GogMaintenance.Proposal?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var recoverablePatch by remember { mutableStateOf(false) }
|
||||
val key = "gog:${game.sidecar.id}"
|
||||
val download = com.droiddeck.launcher.stores.StoresState.download(key)
|
||||
val active = download?.isActive == true
|
||||
val check = GogMaintenance.checks[game.sidecar.id]
|
||||
LaunchedEffect(game.folder.path) { GogMaintenance.check(ctx, game) }
|
||||
LaunchedEffect(menu, active) {
|
||||
if (menu) {
|
||||
recoverablePatch = false
|
||||
val result = withContext(Dispatchers.IO) { runCatching {
|
||||
GogFiles.read(GogFiles.journal(game.folder))?.let {
|
||||
it.optString("operation") == GogOperation.PATCH.name && it.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain")
|
||||
} == true
|
||||
} }
|
||||
result.onSuccess { recoverablePatch = it }.onFailure { error = it.message }
|
||||
}
|
||||
}
|
||||
fun prepare(operation: GogOperation, patch: GogOfflineDownload? = null) {
|
||||
menu = false; patches = null; busy = true; error = null
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { GogMaintenance.prepare(ctx, game, operation, patch) } }
|
||||
.onSuccess { proposal = it }.onFailure { error = it.message }
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
if (active) {
|
||||
ActionChip(downloadLabel(download!!), ok = false)
|
||||
if (download.interruptible) {
|
||||
SecondaryButton(stringResource(if (download.state == DownloadState.PAUSED) R.string.stores_dl_resume else R.string.stores_dl_pause)) {
|
||||
if (download.state == DownloadState.PAUSED) DownloadQueue.resume(ctx, key) else DownloadQueue.pause(key)
|
||||
}
|
||||
} else Text(stringResource(R.string.gog_patch_in_session), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
} else if (!game.sidecar.isInstalled || GogFiles.journal(game.folder).exists()) {
|
||||
SecondaryButton(stringResource(R.string.gog_resume), modifier = Modifier.testTag("gog-resume")) {
|
||||
busy = true
|
||||
scope.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
GogMaintenance.resume(ctx, game)
|
||||
}
|
||||
}.onSuccess { proposal = it }.onFailure { error = it.message }
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
} else if (check?.state == GogMaintenance.State.AVAILABLE) {
|
||||
SecondaryButton(stringResource(R.string.gog_update, check.version.ifBlank { game.sidecar.title }), enabled = !busy, modifier = Modifier.testTag("gog-update")) { prepare(GogOperation.UPDATE) }
|
||||
}
|
||||
androidx.compose.foundation.layout.Box {
|
||||
SecondaryButton(stringResource(if (busy) R.string.common_checking else R.string.gog_maintenance), enabled = !busy && !active, modifier = Modifier.testTag("gog-maintenance")) { menu = !menu }
|
||||
AnchoredMenu(menu, { menu = false }, title = stringResource(R.string.gog_maintenance), compact = true) { first ->
|
||||
MenuItem(stringResource(R.string.common_update), checked = false) { prepare(GogOperation.UPDATE) }
|
||||
MenuItem(stringResource(R.string.gog_check), checked = false, focusRequester = first) { menu = false; GogMaintenance.check(ctx, game, true) }
|
||||
MenuItem(stringResource(R.string.gog_repair), checked = false, modifier = Modifier.testTag("gog-repair")) { prepare(GogOperation.REPAIR) }
|
||||
MenuItem(stringResource(R.string.gog_patches), checked = false, modifier = Modifier.testTag("gog-patches")) {
|
||||
menu = false; busy = true
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { GogMaintenance.offlinePatches(ctx, game) } }
|
||||
.onSuccess { patches = it }.onFailure { error = it.message }
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
MenuItem(stringResource(R.string.gog_refresh), checked = false) { prepare(GogOperation.REFRESH) }
|
||||
if (recoverablePatch) MenuItem(stringResource(R.string.gog_recover), checked = false, modifier = Modifier.testTag("gog-recover")) {
|
||||
menu = false; busy = true
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { GogMaintenance.recoverPatch(ctx, game) } }.onFailure { error = it.message }
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (check?.state == GogMaintenance.State.FAILED || check?.state == GogMaintenance.State.UNKNOWN) {
|
||||
if (check.reason.isNotBlank()) Text(check.reason, fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
patches?.let { list ->
|
||||
val shown = rememberShown { patches = null }
|
||||
val close = { shown.targetState = false }
|
||||
AppDialog(shown, close, "gogPatches", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(stringResource(R.string.gog_patches), close)
|
||||
Text(game.sidecar.title, fontSize = 12.sp, lineHeight = 16.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(stringResource(R.string.gog_patch_requirements), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
|
||||
if (list.isEmpty()) Text(stringResource(R.string.gog_no_patches), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
list.forEach { patch ->
|
||||
ListRow(onClick = { close(); prepare(GogOperation.PATCH, patch) }) {
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(patch.name, fontSize = 13.sp, lineHeight = 18.sp, fontWeight = FontWeight.Medium, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Text(listOf(StoreLanguage.displayName(patch.language).ifBlank { patch.language }, patch.version, formatBytes(patch.size)).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
fontSize = 11.sp, lineHeight = 15.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
Text(stringResource(R.string.gog_select_patch), fontSize = 12.sp, color = LocalPalette.current.signal)
|
||||
}
|
||||
}
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.gog_refresh)) { prepare(GogOperation.REFRESH) }
|
||||
}
|
||||
}
|
||||
proposal?.let { selected ->
|
||||
val shown = rememberShown { proposal = null }
|
||||
val close = { shown.targetState = false }
|
||||
val action = when (selected.operation) {
|
||||
GogOperation.UPDATE -> R.string.common_update
|
||||
GogOperation.REPAIR -> R.string.gog_repair_action
|
||||
GogOperation.PATCH -> R.string.gog_open_patch
|
||||
GogOperation.REFRESH -> R.string.gog_refresh_action
|
||||
}
|
||||
AppDialog(shown, close, "gogMaintenance", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(stringResource(action), close)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(listOf(game.sidecar.title, selected.before.version).filter { it.isNotBlank() }.joinToString(" · "), fontSize = 12.sp, lineHeight = 16.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (selected.operation != GogOperation.REPAIR) Text(selected.patch?.name ?: selected.target.version.ifBlank { selected.target.build }, fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface.copy(alpha = 0.65f)).padding(12.dp)) {
|
||||
GogMetric(stringResource(R.string.gog_download_label), formatBytes(selected.downloadBytes), Modifier.weight(1f))
|
||||
GogMetric(stringResource(if (selected.operation == GogOperation.PATCH || selected.operation == GogOperation.REFRESH) R.string.gog_space_estimate_label else R.string.gog_space_label),
|
||||
formatBytes(selected.diskBytes), Modifier.weight(1f))
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Text(stringResource(R.string.gog_managed_files), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
|
||||
if (selected.fullFiles) Text(stringResource(R.string.gog_full_files), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
|
||||
if (selected.operation == GogOperation.PATCH) Text(stringResource(R.string.gog_patch_installer_note), fontSize = 12.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
PrimaryButton(stringResource(action), enabled = !busy, modifier = Modifier.testTag("gog-apply")) {
|
||||
busy = true
|
||||
close()
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { GogMaintenance.enqueue(ctx, game, selected) } }.onFailure { error = it.message }
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.common_cancel), onClick = close)
|
||||
}
|
||||
}
|
||||
}
|
||||
error?.let { Text(it, fontSize = 12.sp, color = colors.error) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GogMetric(label: String, value: String, modifier: Modifier) {
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(label, fontSize = 11.sp, lineHeight = 15.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(value, fontSize = 15.sp, lineHeight = 20.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,9 @@ import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollection
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollections
|
||||
import com.droiddeck.launcher.stores.itch.ItchUpdates
|
||||
import com.droiddeck.launcher.stores.gog.GogMaintenance
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import com.droiddeck.launcher.stores.retainOrder
|
||||
import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter
|
||||
import com.droiddeck.launcher.stores.sortGames
|
||||
@@ -586,13 +589,17 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) {
|
||||
download != null -> Text("${download.percent}%", fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
e.item != null && StoresState.isUnfinished(e.item) -> Text(stringResource(R.string.stores_resume), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
if (e.installed && e.storeKey?.let { it in ItchUpdates.available } == true) Text(stringResource(R.string.common_update), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
if (e.installed && libraryUpdateAvailable(e)) Text(stringResource(R.string.common_update), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
if (size != null && size > 0) Text(formatBytes(size), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
|
||||
if (!e.installed) Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available } == true ||
|
||||
e.source == Store.GOG.id && (e.item?.id ?: e.game?.storeId)?.let { GogMaintenance.checks[it]?.state } == GogMaintenance.State.AVAILABLE ||
|
||||
e.storeKey?.let { StoreMaintenance.checks[it]?.state == MaintenanceCheckState.AVAILABLE } == true
|
||||
|
||||
@Composable
|
||||
private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, choose: (() -> Unit)?, onOpen: (String) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -613,6 +620,7 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch
|
||||
val size = if (e.installed && folder != null) diskSize(inst, folder) else e.item?.let { StoreSizes.size(it) }?.takeIf { it > 0 }
|
||||
val status = when {
|
||||
download != null -> downloadLabel(download)
|
||||
e.installed && libraryUpdateAvailable(e) -> stringResource(R.string.common_update)
|
||||
!e.installed -> stringResource(R.string.stores_section_not_installed)
|
||||
e.game != null -> playedSpan(e.game.lastPlayed)?.replaceFirstChar { it.uppercase() } ?: stringResource(R.string.games_never_played)
|
||||
else -> stringResource(R.string.stores_installed_chip)
|
||||
|
||||
@@ -846,17 +846,23 @@ private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack:
|
||||
val ctx = LocalContext.current
|
||||
val busy = sessionRunning || StorageState.cleaning
|
||||
var confirm by remember { mutableStateOf<com.droiddeck.launcher.storage.Leftover?>(null) }
|
||||
var confirmPrefix by remember { mutableStateOf<com.droiddeck.launcher.storage.GameUsage?>(null) }
|
||||
SubHeader(stringResource(R.string.storage_game_data), stringResource(R.string.storage_game_data_hint, gb(report.prefixes), gb(report.workshop), gb(report.shaders)), onBack)
|
||||
ActionStatus()
|
||||
if (sessionRunning) { Note(stringResource(R.string.storage_session_running)); Spacer(Modifier.height(4.dp)) }
|
||||
val games = report.games.filter { it.data >= ONE_MB }.sortedByDescending { it.data }
|
||||
val games = report.games.filter { it.data >= ONE_MB || it.prefixDir != null }.sortedByDescending { it.data }
|
||||
SectionTitle(stringResource(R.string.storage_data_installed), gb(games.sumOf { it.data }))
|
||||
ListCard {
|
||||
if (games.isEmpty()) Text(stringResource(R.string.storage_no_games), fontSize = 14.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(16.dp))
|
||||
games.forEachIndexed { i, g ->
|
||||
ItemRow(
|
||||
gameName(g), stringResource(R.string.storage_data_parts, gb(g.prefix), gb(g.shaders), gb(g.workshop)), g.data, i == games.lastIndex,
|
||||
action = { SecondaryButton(stringResource(R.string.storage_clear_shaders), compact = true, enabled = !busy && g.shaders >= ONE_MB) { StorageState.clearShaders(ctx, g.appId, g.x64) } },
|
||||
action = {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
SecondaryButton(stringResource(R.string.storage_clear_shaders), compact = true, enabled = !busy && g.shaders >= ONE_MB) { StorageState.clearShaders(ctx, g.appId, g.x64) }
|
||||
SecondaryButton(stringResource(R.string.storage_reset_prefix), compact = true, enabled = !busy && g.prefixDir != null) { confirmPrefix = g }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -888,6 +894,13 @@ private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack:
|
||||
SectionTitle(stringResource(R.string.storage_data_other), null)
|
||||
ListCard { ItemRow(stringResource(R.string.storage_data_other_title), stringResource(R.string.storage_data_other_detail), report.otherPrefixes, true) }
|
||||
}
|
||||
confirmPrefix?.let { g ->
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.storage_reset_prefix_title, gameName(g)),
|
||||
stringResource(R.string.storage_reset_prefix_confirm, gb(g.prefix), g.library), stringResource(R.string.storage_reset_prefix),
|
||||
onConfirm = { StorageState.resetPrefix(ctx, g) }, onDismiss = { confirmPrefix = null },
|
||||
)
|
||||
}
|
||||
confirm?.let { l ->
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.storage_remove_title, stringResource(R.string.storage_steam_app, l.appId)),
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
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.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceCheckState
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceProposal
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceRecovery
|
||||
import com.droiddeck.launcher.stores.maintenance.RecoveryState
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@Composable
|
||||
internal fun SteamClientMaintenanceActions(actions: FrontEndActions, sessionRunning: Boolean) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (sessionRunning) SecondaryButton("Open Steam downloads", modifier = Modifier.testTag("steam-downloads")) {
|
||||
actions.onSteamUrl("steam://open/downloads")
|
||||
} else SecondaryButton("Start Steam", modifier = Modifier.testTag("steam-start")) { actions.onPlay() }
|
||||
}
|
||||
Text("In Steam, open this game’s Properties → Installed Files → Verify integrity.",
|
||||
fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun StoreMaintenanceActions(game: InstalledStoreGame) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val adapter = StoreMaintenance.adapter(game) ?: return
|
||||
val capabilities = adapter.capabilities(game)
|
||||
val check = StoreMaintenance.checks[game.key]
|
||||
val key = game.key
|
||||
val download = StoresState.download(key)
|
||||
val active = download?.isActive == true
|
||||
var busy by remember(key) { mutableStateOf(false) }
|
||||
var error by remember(key) { mutableStateOf<String?>(null) }
|
||||
var proposal by remember(key) { mutableStateOf<MaintenanceProposal?>(null) }
|
||||
var recovery by remember(key) { mutableStateOf(MaintenanceRecovery()) }
|
||||
var menu by remember(key) { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(game.folder.path) { StoreMaintenance.check(context, game) }
|
||||
LaunchedEffect(game.folder.path, active, download?.state) {
|
||||
recovery = withContext(Dispatchers.IO) { StoreMaintenance.recovery(context, game) }
|
||||
}
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
if (active) {
|
||||
ActionChip(downloadLabel(download!!), ok = false)
|
||||
if (download.interruptible) SecondaryButton(
|
||||
stringResource(if (download.state == com.droiddeck.launcher.stores.download.DownloadState.PAUSED) com.droiddeck.launcher.R.string.stores_dl_resume else com.droiddeck.launcher.R.string.stores_dl_pause),
|
||||
) {
|
||||
if (download.state == com.droiddeck.launcher.stores.download.DownloadState.PAUSED) DownloadQueue.resume(context, key) else DownloadQueue.pause(key)
|
||||
}
|
||||
} else if (recovery.state == RecoveryState.RESUMABLE) {
|
||||
SecondaryButton("Resume", enabled = !busy, modifier = Modifier.testTag("store-resume")) {
|
||||
busy = true
|
||||
scope.launch {
|
||||
try {
|
||||
runCatchingCancellable { withContext(Dispatchers.IO) { StoreMaintenance.resume(context, game) } }
|
||||
.onFailure { error = it.message }
|
||||
} finally { busy = false }
|
||||
}
|
||||
}
|
||||
} else if (MaintenanceAction.UPDATE in capabilities && check?.state == MaintenanceCheckState.AVAILABLE) {
|
||||
val target = check.version.takeIf { it.isNotBlank() }
|
||||
SecondaryButton(target?.let { "Update to $it" } ?: "Update", enabled = !busy, modifier = Modifier.testTag("store-update")) {
|
||||
beginPrepare(MaintenanceAction.UPDATE, context, game, scope, { busy = it }, { proposal = it }, { error = it })
|
||||
}
|
||||
}
|
||||
if (!active) Box {
|
||||
SecondaryButton("Maintenance", enabled = !busy, modifier = Modifier.testTag("store-maintenance")) { menu = !menu }
|
||||
AnchoredMenu(menu, onDismiss = { menu = false }, title = "Maintenance", compact = true) { first ->
|
||||
MenuItem("Check for updates", checked = false, enabled = !busy && game.sidecar.isInstalled,
|
||||
modifier = Modifier.testTag("store-check"), focusRequester = first) {
|
||||
menu = false
|
||||
StoreMaintenance.check(context, game, force = true)
|
||||
}
|
||||
if (MaintenanceAction.UPDATE in capabilities) {
|
||||
val legacyBootstrap = game.sidecar.store in setOf(com.droiddeck.launcher.stores.Store.EPIC, com.droiddeck.launcher.stores.Store.AMAZON) &&
|
||||
check?.state != MaintenanceCheckState.AVAILABLE
|
||||
MenuItem(if (legacyBootstrap) "Update / verify current build" else "Update", checked = false, enabled = !busy,
|
||||
modifier = Modifier.testTag("store-update-menu")) {
|
||||
beginPrepare(MaintenanceAction.UPDATE, context, game, scope, { busy = it }, { proposal = it }, { error = it })
|
||||
}
|
||||
}
|
||||
if (MaintenanceAction.REPAIR in capabilities) MenuItem("Verify / Repair", checked = false, enabled = !busy,
|
||||
modifier = Modifier.testTag("store-repair")) {
|
||||
beginPrepare(MaintenanceAction.REPAIR, context, game, scope, { busy = it }, { proposal = it }, { error = it })
|
||||
}
|
||||
if (MaintenanceAction.REFRESH in capabilities) MenuItem("Refresh", checked = false, enabled = !busy,
|
||||
modifier = Modifier.testTag("store-refresh")) {
|
||||
beginPrepare(MaintenanceAction.REFRESH, context, game, scope, { busy = it }, { proposal = it }, { error = it })
|
||||
}
|
||||
if (MaintenanceAction.OPEN_CLIENT in capabilities) MenuItem(adapter.openClientLabel(game), checked = false, enabled = !busy,
|
||||
modifier = Modifier.testTag("store-open-client")) {
|
||||
menu = false
|
||||
runCatching { StoreMaintenance.openClient(context, game) }.onFailure { error = it.message }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!active && recovery.state == RecoveryState.NEEDS_ATTENTION && recovery.message.isNotBlank())
|
||||
Text(recovery.message, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
check?.let { current ->
|
||||
when (current.state) {
|
||||
MaintenanceCheckState.CHECKING -> Text("Checking for updates…", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
MaintenanceCheckState.CURRENT -> Text("Up to date", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
MaintenanceCheckState.AVAILABLE -> if (MaintenanceAction.UPDATE !in capabilities) {
|
||||
val message = if (MaintenanceAction.OPEN_CLIENT in capabilities) {
|
||||
"An update is available. Use ${adapter.openClientLabel(game)} to apply it."
|
||||
} else {
|
||||
"An update is available."
|
||||
}
|
||||
Text(message,
|
||||
fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
MaintenanceCheckState.UNKNOWN, MaintenanceCheckState.FAILED -> if (current.reason.isNotBlank())
|
||||
Text(current.reason, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
error?.let { Text(it, fontSize = 12.sp, color = MaterialTheme.colorScheme.error) }
|
||||
|
||||
proposal?.let { selected ->
|
||||
val shown = rememberShown { proposal = null }
|
||||
val close = { shown.targetState = false }
|
||||
AppDialog(shown, close, "storeMaintenance", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(selected.operation.label(), close)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Text(game.sidecar.title, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(selected.targetLabel, fontSize = 15.sp, color = MaterialTheme.colorScheme.onBackground)
|
||||
if (selected.description.isNotBlank()) Text(selected.description, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp)) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Download", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(maintenanceEstimate(selected.downloadBytes), fontSize = 14.sp)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Required space", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(maintenanceEstimate(selected.diskBytes), fontSize = 14.sp)
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
PrimaryButton(selected.operation.label(), enabled = !busy) {
|
||||
busy = true
|
||||
close()
|
||||
scope.launch {
|
||||
try {
|
||||
runCatchingCancellable { withContext(Dispatchers.IO) { StoreMaintenance.enqueue(context, game, selected) } }
|
||||
.onFailure { error = it.message }
|
||||
} finally { busy = false }
|
||||
}
|
||||
}
|
||||
SecondaryButton("Cancel", onClick = close)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun beginPrepare(
|
||||
action: MaintenanceAction,
|
||||
context: android.content.Context,
|
||||
game: InstalledStoreGame,
|
||||
scope: kotlinx.coroutines.CoroutineScope,
|
||||
setBusy: (Boolean) -> Unit,
|
||||
setProposal: (MaintenanceProposal) -> Unit,
|
||||
setError: (String?) -> Unit,
|
||||
) {
|
||||
setBusy(true)
|
||||
scope.launch {
|
||||
try {
|
||||
runCatchingCancellable { withContext(Dispatchers.IO) { StoreMaintenance.prepare(context, game, action) } }
|
||||
.onSuccess(setProposal).onFailure { setError(it.message) }
|
||||
} finally { setBusy(false) }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <T> runCatchingCancellable(block: suspend () -> T): Result<T> = try {
|
||||
Result.success(block())
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (error: Throwable) {
|
||||
Result.failure(error)
|
||||
}
|
||||
|
||||
private fun MaintenanceAction.label(): String = when (this) {
|
||||
MaintenanceAction.UPDATE -> "Update"
|
||||
MaintenanceAction.REPAIR -> "Repair files"
|
||||
MaintenanceAction.REFRESH -> "Refresh installation"
|
||||
MaintenanceAction.OPEN_CLIENT -> "Open client"
|
||||
}
|
||||
|
||||
private fun maintenanceEstimate(bytes: Long): String =
|
||||
if (bytes < 0L) "Unknown (client-determined)" else com.droiddeck.launcher.stores.formatBytes(bytes)
|
||||
@@ -360,8 +360,10 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
when (d.state) {
|
||||
DownloadState.RUNNING, DownloadState.QUEUED -> {
|
||||
RoundAction(Icons.Filled.Pause, stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(d.key) }
|
||||
CancelAction { DownloadQueue.cancel(ctx, d.key) }
|
||||
if (d.interruptible) {
|
||||
RoundAction(Icons.Filled.Pause, stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(d.key) }
|
||||
CancelAction { DownloadQueue.cancel(ctx, d.key) }
|
||||
}
|
||||
}
|
||||
DownloadState.PAUSED -> {
|
||||
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.resume(ctx, d.key) }
|
||||
|
||||
@@ -1380,6 +1380,9 @@ private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droi
|
||||
val pal = LocalPalette.current
|
||||
val small = 10.sp
|
||||
when {
|
||||
item.store == Store.GOG && download != null -> Text("${download.percent}%", fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
item.store == Store.GOG && installed && com.droiddeck.launcher.stores.gog.GogMaintenance.checks[item.id]?.state == com.droiddeck.launcher.stores.gog.GogMaintenance.State.AVAILABLE ->
|
||||
Text(stringResource(R.string.common_update), fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
installed -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
val ctx = LocalContext.current
|
||||
val game = StoresState.installedGame(item.store, item.id)
|
||||
|
||||
@@ -1256,6 +1256,7 @@
|
||||
<string name="game_link_invalid">Enlace de inicio de juego no válido.</string>
|
||||
<string name="game_link_missing">Este juego ya no está en tu biblioteca de DroidDeck.</string>
|
||||
<string name="game_link_session_busy">Detén la sesión actual antes de iniciar un juego de Steam.</string>
|
||||
<string name="store_maintenance_launch_blocked">El mantenimiento está en curso. Termínalo antes de iniciar este juego.</string>
|
||||
<string name="game_link_failed">No se pudo enviar el juego a Steam. Intenta iniciarlo de nuevo.</string>
|
||||
<string name="setup_retry_removal">Reintentar eliminación</string>
|
||||
<string name="runtime_removing">Eliminando</string>
|
||||
|
||||
@@ -1201,6 +1201,7 @@
|
||||
<string name="game_link_invalid">Enlace de inicio de juego no válido.</string>
|
||||
<string name="game_link_missing">Este juego ya no está en tu biblioteca de DroidDeck.</string>
|
||||
<string name="game_link_session_busy">Detén la sesión actual antes de iniciar un juego de Steam.</string>
|
||||
<string name="store_maintenance_launch_blocked">Hay una tarea de mantenimiento en curso. Termínala antes de iniciar este juego.</string>
|
||||
<string name="game_link_failed">No se pudo enviar el juego a Steam. Intenta iniciarlo de nuevo.</string>
|
||||
<string name="setup_retry_removal">Reintentar eliminación</string>
|
||||
<string name="runtime_removing">Eliminando</string>
|
||||
|
||||
@@ -1,5 +1,25 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="gog_maintenance">Manage GOG installation</string>
|
||||
<string name="gog_check">Check for updates</string>
|
||||
<string name="gog_repair">Verify/Repair</string>
|
||||
<string name="gog_patches">Offline patches</string>
|
||||
<string name="gog_refresh">Download full offline installer</string>
|
||||
<string name="gog_update">Update to %1$s</string>
|
||||
<string name="gog_resume">Resume GOG maintenance</string>
|
||||
<string name="store_maintenance_launch_blocked">Maintenance is running. Finish it before launching this game.</string>
|
||||
<string name="gog_open_patch">Open patch installer</string>
|
||||
<string name="gog_patch_in_session">Finish or cancel the patch installer in the Linux session.</string>
|
||||
<string name="gog_patch_requirements">Choose a patch for your installed version and language. Supported source versions may not be listed.</string>
|
||||
<string name="gog_no_patches">GOG has no standalone Windows patches for this game.</string>
|
||||
<string name="gog_managed_files">Modified game files may be replaced.</string>
|
||||
<string name="gog_patch_installer_note">The installer opens in your Linux session.</string>
|
||||
<string name="gog_download_label">Download</string>
|
||||
<string name="gog_space_label">Extra space</string>
|
||||
<string name="gog_space_estimate_label">Space estimate</string>
|
||||
<string name="gog_repair_action">Repair files</string>
|
||||
<string name="gog_refresh_action">Refresh installation</string>
|
||||
<string name="gog_select_patch">Select</string>
|
||||
<string name="glasses_experimental">Luma Ultra cameras — Experimental</string>
|
||||
<string name="glasses_joycons">Joy-Con position tracking</string>
|
||||
<string name="glasses_joycons_hint">Use the glasses cameras to position your paired Joy-Cons. Rotation and button inputs come from the Joy-Cons. Position is estimated when your wrists are hidden. Replaces bare-hand controllers and pauses phone-camera tracking. Point the Joy-Cons forward when connecting or recentering.</string>
|
||||
@@ -997,6 +1017,8 @@
|
||||
<string name="pairguide_build_number">In About phone, tap Build number 7 times</string>
|
||||
<string name="pairguide_wireless">Turn on Wireless debugging</string>
|
||||
<string name="pairguide_pair">Open Wireless debugging, then tap “Pair device with pairing code”</string>
|
||||
<string name="pairguide_child_process">Turn on “Disable child process restrictions”</string>
|
||||
<string name="pairguide_row_child_process">Disable child process restrictions</string>
|
||||
<string name="pairguide_row_build_number">Build number</string>
|
||||
<string name="pairguide_row_wireless">Wireless debugging</string>
|
||||
<string name="pairguide_row_pair">Pair device with pairing code</string>
|
||||
@@ -1325,6 +1347,8 @@
|
||||
<string name="game_link_missing">This game is no longer in your DroidDeck library.</string>
|
||||
<string name="game_link_session_busy">Stop the current session before launching a Steam game.</string>
|
||||
<string name="game_link_failed">Could not send the game to Steam. Try launching it again.</string>
|
||||
<string name="steam_navigation_switch_mode">Switch to Steam mode to open Steam navigation.</string>
|
||||
<string name="steam_navigation_failed">Could not open that Steam page. Return to Steam mode and try again.</string>
|
||||
<string name="setup_retry_removal">Retry removal</string>
|
||||
<string name="runtime_removing">Removing</string>
|
||||
<string name="runtime_removal_incomplete">Removal incomplete</string>
|
||||
@@ -2959,6 +2983,9 @@
|
||||
<string name="storage_data_installed">Installed games</string>
|
||||
<string name="storage_data_parts">Prefix %1$s · shaders %2$s · workshop %3$s</string>
|
||||
<string name="storage_clear_shaders">Clear shaders</string>
|
||||
<string name="storage_reset_prefix">Reset prefix</string>
|
||||
<string name="storage_reset_prefix_title">Reset prefix for %1$s?</string>
|
||||
<string name="storage_reset_prefix_confirm">Deletes its Wine prefix (%1$s) in %2$s and recreates it on the next launch. Saves, settings and installed redistributables inside it are lost; Steam Cloud saves stay in your account.</string>
|
||||
<string name="storage_data_leftovers">Uninstalled games</string>
|
||||
<string name="storage_steam_app">Steam app %1$d</string>
|
||||
<string name="storage_leftover_unsure_detail">Its prefix still holds files, which can include local saves</string>
|
||||
@@ -3320,4 +3347,6 @@
|
||||
<string name="integration_shortcuts_service">DroidDeck Home button</string>
|
||||
<string name="integration_shortcuts_service_description">Pass Home button presses to Steam Guide while a Steam session is focused and DroidDeck is the default Home app. Does not read screen content.</string>
|
||||
<string name="integration_brightness_needed">Turn on Brightness in Setup → Steam integration</string>
|
||||
<string name="gog_full_files">Native optimizations are unavailable. The download includes complete replacement files.</string>
|
||||
<string name="gog_recover">Verify patch result</string>
|
||||
</resources>
|
||||
Generated
+23
@@ -1,3 +1,5 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
@@ -186,6 +188,7 @@ dependencies = [
|
||||
name = "droiddeckstores"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"flate2",
|
||||
"futures-util",
|
||||
"jni",
|
||||
@@ -195,6 +198,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha1",
|
||||
"sha2",
|
||||
"sha3",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
@@ -590,6 +594,15 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keccak"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.186"
|
||||
@@ -986,6 +999,16 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha3"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"keccak",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "1.3.0"
|
||||
|
||||
@@ -20,6 +20,10 @@ futures-util = { version = "0.3", default-features = false, features = ["std"] }
|
||||
serde_json = { version = "1", features = ["preserve_order"] }
|
||||
sha1 = "0.10"
|
||||
sha2 = "0.10"
|
||||
sha3 = "0.10"
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1"
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
|
||||
@@ -77,14 +77,14 @@ after it (marker files, exe resolution, DLC markers, redist orchestration).
|
||||
| `nativeCancel(handle: Long)` | `(J)V` | `Java_com_droiddeck_launcher_stores_gog_GogNative_nativeCancel` |
|
||||
| `nativeRelease(handle: Long)` | `(J)V` | `Java_com_droiddeck_launcher_stores_gog_GogNative_nativeRelease` |
|
||||
|
||||
`nativeProbe()` always returns `1`; it exists so `isAvailable()` can catch `UnsatisfiedLinkError`
|
||||
`nativeProbe()` returns `2`; it exists so `isAvailable()` can catch `UnsatisfiedLinkError`
|
||||
once at startup instead of mid-download.
|
||||
|
||||
`nativeStart` parameters, in order:
|
||||
|
||||
| # | Parameter | Meaning |
|
||||
|---|---|---|
|
||||
| 1 | `kind: Int` | `0` = `KIND_GEN2_CHUNKS`, `1` = `KIND_GEN1_RANGES` (anything else → gen2) |
|
||||
| 1 | `kind: Int` | `0` = `KIND_GEN2_CHUNKS`, `1` = `KIND_GEN1_RANGES`, `2` = GOG maintenance (anything else → gen2) |
|
||||
| 2 | `depotManifests: Array<String>` | gen2: the inflated depot-manifest JSON strings, in fetch order, already filtered by product + language; gen1: the inflated build manifest (one element) |
|
||||
| 3 | `cdnBases: Array<String>` | gen2: **every** CDN base of the secure-link answer — one per `urls[]` entry, each resolved the way `parseCdnUrl` resolves `urls[0]` today (query string intact), in GOG's order — or the one unauthenticated dependency store base (an array of one); gen1: `emptyArray()` (file URLs are in the manifest). Blank entries are ignored and a base whose host already appeared is dropped (the first wins). The fetch core spreads the window across the distinct hosts with a per-host cap of `max(6, ceil(maxWorkers / hosts))`, rotating a failed chunk to another CDN; one base behaves exactly like the old single `cdnBase`. The start log line lists them as `hosts=a,b,c`. |
|
||||
| 4 | `installDir: String` | absolute install directory |
|
||||
@@ -113,6 +113,15 @@ On-disk protocol (what a resumed run, by either engine, relies on): a file is as
|
||||
`<file>.bhtmp`, then renamed over `<file>` once its size and MD5 match the manifest; an existing
|
||||
`<file>` whose size+MD5 match is skipped. The engine writes nothing else.
|
||||
|
||||
Maintenance (`kind=2`) instead takes a single normalized plan in `depotManifests[0]`:
|
||||
`files`, `oldFiles`, optional exact-build `patches`, per-product `links` and `patchLinks`,
|
||||
and estimated `downloadBytes`. Credentials and these temporary links stay in memory.
|
||||
It stages replacements under `.droiddeck-gog/stage`, revalidates completed chunks on
|
||||
every run, and verifies each file before atomic replacement. `onBytes` counts actual
|
||||
network bytes, including failed attempts. `onMaintenance(networkBytes, reusedBytes,
|
||||
appliedBytes)` (`(JJJ)V`) reports the three separate cumulative counters. Existing
|
||||
gen1/gen2 first-install progress semantics are unchanged.
|
||||
|
||||
## `com.droiddeck.launcher.stores.epic.EpicNative`
|
||||
|
||||
Everything Epic runs in the Rust `epic` module: the web-service calls (sign-in, refresh, exchange
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
fn main() {
|
||||
cc::Build::new()
|
||||
.include("vendor/xdelta3")
|
||||
.file("vendor/xdelta3/xdelta3.c")
|
||||
.file("src/gog/delta.c")
|
||||
.define("SIZEOF_SIZE_T", "8")
|
||||
.define("SIZEOF_UNSIGNED_INT", "4")
|
||||
.define("SIZEOF_UNSIGNED_LONG", "8")
|
||||
.define("SIZEOF_UNSIGNED_LONG_LONG", "8")
|
||||
.define("XD3_USE_LARGEFILE64", "1")
|
||||
.define("XD3_ENCODER", "0")
|
||||
.define("SECONDARY_DJW", "0")
|
||||
.define("SECONDARY_FGK", "0")
|
||||
.define("SECONDARY_LZMA", "0")
|
||||
.define("SHELL_TESTS", "0")
|
||||
.define("XD3_MAIN", "0")
|
||||
.warnings(false)
|
||||
.compile("gogdelta");
|
||||
println!("cargo:rerun-if-changed=vendor/xdelta3");
|
||||
println!("cargo:rerun-if-changed=src/gog/delta.c");
|
||||
}
|
||||
@@ -4,6 +4,10 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use sha3::{
|
||||
digest::{ExtendableOutput, Update},
|
||||
Shake128,
|
||||
};
|
||||
|
||||
use crate::amazon::manifest::{GameFile, TEMP_SUFFIX};
|
||||
|
||||
@@ -15,7 +19,9 @@ pub enum State {
|
||||
}
|
||||
|
||||
pub fn sha256_of(path: &Path, cancel: &AtomicBool) -> Result<Option<[u8; 32]>, ()> {
|
||||
let Ok(mut f) = fs::File::open(path) else { return Ok(None) };
|
||||
let Ok(mut f) = fs::File::open(path) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buf = vec![0u8; 1024 * 1024];
|
||||
loop {
|
||||
@@ -24,22 +30,73 @@ pub fn sha256_of(path: &Path, cancel: &AtomicBool) -> Result<Option<[u8; 32]>, (
|
||||
}
|
||||
match f.read(&mut buf) {
|
||||
Ok(0) => return Ok(Some(hasher.finalize().into())),
|
||||
Ok(n) => hasher.update(&buf[..n]),
|
||||
Ok(n) => Digest::update(&mut hasher, &buf[..n]),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
|
||||
Err(_) => return Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hash_matches(path: &Path, file: &GameFile, cancel: &AtomicBool) -> Result<Option<bool>, ()> {
|
||||
if !file.has_supported_hash() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Ok(mut f) = fs::File::open(path) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut buf = vec![0u8; 1024 * 1024];
|
||||
match file.algorithm {
|
||||
0 => {
|
||||
let mut h = Sha256::new();
|
||||
loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err(());
|
||||
}
|
||||
match f.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => Digest::update(&mut h, &buf[..n]),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
|
||||
Err(_) => return Ok(None),
|
||||
}
|
||||
}
|
||||
Ok(Some(h.finalize().as_slice() == file.digest.as_slice()))
|
||||
}
|
||||
1 => {
|
||||
let mut h = Shake128::default();
|
||||
loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err(());
|
||||
}
|
||||
match f.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => Update::update(&mut h, &buf[..n]),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
|
||||
Err(_) => return Ok(None),
|
||||
}
|
||||
}
|
||||
let mut reader = h.finalize_xof();
|
||||
let mut got = vec![0u8; file.digest.len()];
|
||||
std::io::Read::read(&mut reader, &mut got).map_err(|_| ())?;
|
||||
Ok(Some(got == file.digest))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn state(dest: &Path, file: &GameFile, cancel: &AtomicBool) -> State {
|
||||
if file.size == 0 && file.digest.is_empty() {
|
||||
return match fs::symlink_metadata(dest) {
|
||||
Ok(m) if m.is_file() && m.len() == 0 => State::Complete,
|
||||
_ => State::Pending,
|
||||
};
|
||||
}
|
||||
match fs::symlink_metadata(dest) {
|
||||
Ok(m) if m.is_file() && m.len() == file.size => {}
|
||||
_ => return State::Pending,
|
||||
}
|
||||
let Some(expected) = file.sha256() else { return State::Complete };
|
||||
match sha256_of(dest, cancel) {
|
||||
match hash_matches(dest, file, cancel) {
|
||||
Err(()) => State::Cancelled,
|
||||
Ok(Some(got)) if got == expected => State::Complete,
|
||||
Ok(Some(true)) => State::Complete,
|
||||
Ok(_) => State::Pending,
|
||||
}
|
||||
}
|
||||
@@ -54,7 +111,11 @@ pub fn remove_stray_temps(game_dir: &Path, files: &[GameFile]) -> usize {
|
||||
files
|
||||
.iter()
|
||||
.map(|f| temp_path(&game_dir.join(&f.path)))
|
||||
.filter(|t| fs::symlink_metadata(t).map(|m| m.is_file() || m.file_type().is_symlink()).unwrap_or(false))
|
||||
.filter(|t| {
|
||||
fs::symlink_metadata(t)
|
||||
.map(|m| m.is_file() || m.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.filter(|t| fs::remove_file(t).is_ok())
|
||||
.count()
|
||||
}
|
||||
@@ -73,7 +134,9 @@ pub fn free_bytes(path: &Path) -> i64 {
|
||||
#[cfg(unix)]
|
||||
fn available(path: &Path) -> i64 {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let Ok(c) = std::ffi::CString::new(path.as_os_str().as_bytes()) else { return -1 };
|
||||
let Ok(c) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
|
||||
return -1;
|
||||
};
|
||||
let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
|
||||
if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 {
|
||||
return -1;
|
||||
@@ -111,7 +174,12 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn file(path: &str, size: u64, digest: Vec<u8>) -> GameFile {
|
||||
GameFile { path: path.into(), size, algorithm: 0, digest }
|
||||
GameFile {
|
||||
path: path.into(),
|
||||
size,
|
||||
algorithm: 0,
|
||||
digest,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -123,15 +191,76 @@ mod tests {
|
||||
fs::write(&p, b"hello").unwrap();
|
||||
let good = Sha256::digest(b"hello").to_vec();
|
||||
let cancel = AtomicBool::new(false);
|
||||
assert_eq!(state(&p, &file("a.bin", 5, good.clone()), &cancel), State::Complete);
|
||||
assert_eq!(state(&p, &file("a.bin", 5, Sha256::digest(b"HELLO").to_vec()), &cancel), State::Pending);
|
||||
assert_eq!(state(&p, &file("a.bin", 6, good.clone()), &cancel), State::Pending);
|
||||
let other = GameFile { path: "a.bin".into(), size: 5, algorithm: 3, digest: vec![1, 2] };
|
||||
assert_eq!(state(&p, &other, &cancel), State::Complete, "no SHA-256: size decides");
|
||||
assert_eq!(state(&dir, &file("x", 0, vec![]), &cancel), State::Pending, "a directory is not a file");
|
||||
assert_eq!(state(&dir.join("missing"), &file("m", 0, vec![]), &cancel), State::Pending);
|
||||
assert_eq!(
|
||||
state(&p, &file("a.bin", 5, good.clone()), &cancel),
|
||||
State::Complete
|
||||
);
|
||||
assert_eq!(
|
||||
state(
|
||||
&p,
|
||||
&file("a.bin", 5, Sha256::digest(b"HELLO").to_vec()),
|
||||
&cancel
|
||||
),
|
||||
State::Pending
|
||||
);
|
||||
assert_eq!(
|
||||
state(&p, &file("a.bin", 6, good.clone()), &cancel),
|
||||
State::Pending
|
||||
);
|
||||
let other = GameFile {
|
||||
path: "a.bin".into(),
|
||||
size: 5,
|
||||
algorithm: 3,
|
||||
digest: vec![1, 2],
|
||||
};
|
||||
assert_eq!(
|
||||
state(&p, &other, &cancel),
|
||||
State::Pending,
|
||||
"unsupported hashes cannot establish file integrity"
|
||||
);
|
||||
assert_eq!(
|
||||
state(&dir, &file("x", 0, vec![]), &cancel),
|
||||
State::Pending,
|
||||
"a directory is not a file"
|
||||
);
|
||||
assert_eq!(
|
||||
state(&dir.join("missing"), &file("m", 0, vec![]), &cancel),
|
||||
State::Pending
|
||||
);
|
||||
cancel.store(true, Ordering::Relaxed);
|
||||
assert_eq!(state(&p, &file("a.bin", 5, good), &cancel), State::Cancelled);
|
||||
assert_eq!(
|
||||
state(&p, &file("a.bin", 5, good), &cancel),
|
||||
State::Cancelled
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shake128_checks_the_manifest_digest_length() {
|
||||
use sha3::{
|
||||
digest::{ExtendableOutput, Update},
|
||||
Shake128,
|
||||
};
|
||||
let dir = std::env::temp_dir().join(format!("dd-amazon-shake-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let p = dir.join("a.bin");
|
||||
fs::write(&p, b"hello").unwrap();
|
||||
let mut hasher = Shake128::default();
|
||||
Update::update(&mut hasher, b"hello");
|
||||
let mut reader = hasher.finalize_xof();
|
||||
let mut digest = vec![0; 32];
|
||||
std::io::Read::read(&mut reader, &mut digest).unwrap();
|
||||
let file = GameFile {
|
||||
path: "a.bin".into(),
|
||||
size: 5,
|
||||
algorithm: 1,
|
||||
digest: digest.clone(),
|
||||
};
|
||||
let cancel = AtomicBool::new(false);
|
||||
assert_eq!(state(&p, &file, &cancel), State::Complete);
|
||||
fs::write(&p, b"HELLO").unwrap();
|
||||
assert_eq!(state(&p, &file, &cancel), State::Pending);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -142,7 +271,10 @@ mod tests {
|
||||
fs::create_dir_all(dir.join("sub")).unwrap();
|
||||
fs::write(dir.join("sub/a.bin.tmp"), b"x").unwrap();
|
||||
fs::write(dir.join("save.tmp"), b"keep").unwrap();
|
||||
let files = vec![file("sub/a.bin", 1, vec![0; 32]), file("b.bin", 1, vec![0; 32])];
|
||||
let files = vec![
|
||||
file("sub/a.bin", 1, vec![0; 32]),
|
||||
file("b.bin", 1, vec![0; 32]),
|
||||
];
|
||||
assert_eq!(temp_path(&dir.join("sub/a.bin")), dir.join("sub/a.bin.tmp"));
|
||||
assert_eq!(remove_stray_temps(&dir, &files), 1);
|
||||
assert!(!dir.join("sub/a.bin.tmp").exists());
|
||||
|
||||
@@ -21,7 +21,10 @@ pub const NOT_SIGNED_IN: &str = "Not signed in to Amazon Games";
|
||||
pub const NO_DOWNLOAD: &str = "Amazon gave no download for this game";
|
||||
pub const NO_MANIFEST: &str = "The manifest could not be downloaded";
|
||||
pub const FILE_FAILED: &str = "A file failed to download";
|
||||
pub const REPLACE_REFUSED: &str = "The install record could not be switched to updating; nothing was replaced";
|
||||
pub const NO_VERIFIABLE_HASH: &str =
|
||||
"Amazon's manifest uses a file hash that DroidDeck cannot verify";
|
||||
pub const REPLACE_REFUSED: &str =
|
||||
"The install record could not be switched to updating; nothing was replaced";
|
||||
|
||||
const CHECK_REPORT_EVERY: Duration = Duration::from_millis(200);
|
||||
|
||||
@@ -66,6 +69,8 @@ pub struct Request {
|
||||
pub access_token: String,
|
||||
pub entitlement_id: String,
|
||||
pub game_dir: PathBuf,
|
||||
pub target_manifest_path: Option<PathBuf>,
|
||||
pub target_version_id: Option<String>,
|
||||
pub max_workers: usize,
|
||||
pub process_workers: usize,
|
||||
pub ca_bundle: String,
|
||||
@@ -89,6 +94,14 @@ impl Request {
|
||||
access_token: access_token.to_string(),
|
||||
entitlement_id: entitlement_id.to_string(),
|
||||
game_dir: PathBuf::from(game_dir),
|
||||
target_manifest_path: match net::str_of(v, "targetManifestPath") {
|
||||
"" => None,
|
||||
path => Some(PathBuf::from(path)),
|
||||
},
|
||||
target_version_id: match net::str_of(v, "targetVersionId") {
|
||||
"" => None,
|
||||
version => Some(version.to_string()),
|
||||
},
|
||||
max_workers: v.get("maxWorkers").and_then(|n| n.as_u64()).unwrap_or(8) as usize,
|
||||
process_workers: v.get("processWorkers").and_then(|n| n.as_u64()).unwrap_or(2) as usize,
|
||||
ca_bundle: net::str_of(v, "caBundle").to_string(),
|
||||
@@ -125,11 +138,12 @@ fn cancelled(cancel: &AtomicBool) -> Result<(), Stop> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_manifest(download: &Download, access_token: &str, log: &dyn Fn(&str)) -> Result<manifest::Manifest, String> {
|
||||
let bytes = cdn::fetch_manifest(&download.base_url, access_token).map_err(|e| {
|
||||
log(&format!("manifest download: {e}"));
|
||||
NO_MANIFEST.to_string()
|
||||
})?;
|
||||
pub fn load_manifest(
|
||||
download: &Download,
|
||||
access_token: &str,
|
||||
log: &dyn Fn(&str),
|
||||
) -> Result<manifest::Manifest, String> {
|
||||
let bytes = load_manifest_bytes(download, access_token, log)?;
|
||||
manifest::parse(&bytes).map_err(|e| {
|
||||
log(&format!("manifest parse: {e}"));
|
||||
if e.starts_with("The manifest") {
|
||||
@@ -140,6 +154,175 @@ pub fn load_manifest(download: &Download, access_token: &str, log: &dyn Fn(&str)
|
||||
})
|
||||
}
|
||||
|
||||
fn load_manifest_bytes(
|
||||
download: &Download,
|
||||
access_token: &str,
|
||||
log: &dyn Fn(&str),
|
||||
) -> Result<Vec<u8>, String> {
|
||||
cdn::fetch_manifest(&download.base_url, access_token).map_err(|e| {
|
||||
log(&format!("manifest download: {e}"));
|
||||
NO_MANIFEST.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
fn metadata_dir(game_dir: &PathBuf) -> PathBuf {
|
||||
game_dir.join(".droiddeck-maintenance/amazon")
|
||||
}
|
||||
|
||||
fn read_target_manifest(req: &Request) -> Result<Option<Vec<u8>>, String> {
|
||||
let Some(path) = &req.target_manifest_path else {
|
||||
return Ok(None);
|
||||
};
|
||||
let root = req
|
||||
.game_dir
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("Could not resolve the install folder: {e}"))?;
|
||||
if fs::symlink_metadata(path)
|
||||
.map(|m| m.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err("The pinned Amazon manifest is a symbolic link".into());
|
||||
}
|
||||
let candidate = path
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("The pinned Amazon manifest is unavailable: {e}"))?;
|
||||
if !candidate.starts_with(&root) || !candidate.is_file() {
|
||||
return Err("The pinned Amazon manifest is outside the install folder".into());
|
||||
}
|
||||
fs::read(candidate)
|
||||
.map(Some)
|
||||
.map_err(|e| format!("Could not read the pinned Amazon manifest: {e}"))
|
||||
}
|
||||
|
||||
fn write_installed_manifest(game_dir: &PathBuf, bytes: &[u8]) -> Result<(), String> {
|
||||
let metadata = game_dir.join(".droiddeck-maintenance");
|
||||
if fs::symlink_metadata(&metadata)
|
||||
.map(|m| m.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err("Amazon maintenance metadata is a symbolic link".into());
|
||||
}
|
||||
let dir = metadata_dir(game_dir);
|
||||
if fs::symlink_metadata(&dir)
|
||||
.map(|m| m.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err("Amazon maintenance metadata is a symbolic link".into());
|
||||
}
|
||||
fs::create_dir_all(&dir)
|
||||
.map_err(|e| format!("Could not save the Amazon install manifest: {e}"))?;
|
||||
let temp = dir.join("installed.manifest.tmp");
|
||||
if fs::symlink_metadata(&temp)
|
||||
.map(|m| m.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err("Amazon maintenance metadata is a symbolic link".into());
|
||||
}
|
||||
fs::write(&temp, bytes)
|
||||
.map_err(|e| format!("Could not save the Amazon install manifest: {e}"))?;
|
||||
fs::rename(&temp, dir.join("installed.manifest"))
|
||||
.map_err(|e| format!("Could not save the Amazon install manifest: {e}"))
|
||||
}
|
||||
|
||||
fn read_installed_manifest(game_dir: &PathBuf, log: &dyn Fn(&str)) -> Option<manifest::Manifest> {
|
||||
let path = metadata_dir(game_dir).join("installed.manifest");
|
||||
match fs::symlink_metadata(&path) {
|
||||
Ok(meta) if meta.is_file() && !meta.file_type().is_symlink() => {}
|
||||
Ok(_) => {
|
||||
log("obsolete Amazon files preserved: retained manifest is not a regular file");
|
||||
return None;
|
||||
}
|
||||
Err(_) => return None,
|
||||
}
|
||||
match fs::read(path).ok().and_then(|bytes| manifest::parse(&bytes).ok()) {
|
||||
Some(manifest) => Some(manifest),
|
||||
None => {
|
||||
log("obsolete Amazon files preserved: retained manifest is unavailable or invalid");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cleanup_obsolete(
|
||||
game_dir: &PathBuf,
|
||||
old: &[GameFile],
|
||||
new: &[GameFile],
|
||||
cancel: &AtomicBool,
|
||||
gate: &ReplaceGate,
|
||||
ev: &dyn Events,
|
||||
log: &dyn Fn(&str),
|
||||
) -> Result<bool, Stop> {
|
||||
let key = |path: &str| -> Option<String> {
|
||||
let normalized = manifest::check_path(path).ok()?;
|
||||
Some(normalized.to_lowercase())
|
||||
};
|
||||
let inventory = |files: &[GameFile]| -> Option<std::collections::HashSet<String>> {
|
||||
let mut out = std::collections::HashSet::new();
|
||||
for file in files {
|
||||
if !out.insert(key(&file.path)?) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
};
|
||||
let Some(old_keys) = inventory(old) else {
|
||||
log("obsolete Amazon files preserved: old inventory contains unsafe or case-colliding paths");
|
||||
return Ok(cancel.load(Ordering::Relaxed));
|
||||
};
|
||||
let Some(new_keys) = inventory(new) else {
|
||||
log("obsolete Amazon files preserved: target inventory contains unsafe or case-colliding paths");
|
||||
return Ok(cancel.load(Ordering::Relaxed));
|
||||
};
|
||||
let _ = old_keys;
|
||||
let Ok(root) = game_dir.canonicalize() else {
|
||||
log("obsolete Amazon files preserved: install folder could not be resolved");
|
||||
return Ok(cancel.load(Ordering::Relaxed));
|
||||
};
|
||||
let mut removed = 0usize;
|
||||
let mut preserved = 0usize;
|
||||
for file in old {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
log("obsolete Amazon cleanup cancelled; remaining files were preserved");
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(k) = key(&file.path) else { preserved += 1; continue };
|
||||
if new_keys.contains(&k) { continue; }
|
||||
if !file.has_supported_hash() && !(file.size == 0 && file.digest.is_empty()) {
|
||||
preserved += 1;
|
||||
continue;
|
||||
}
|
||||
let mut path = game_dir.clone();
|
||||
let mut safe = true;
|
||||
for segment in file.path.split('/') {
|
||||
path.push(segment);
|
||||
if fs::symlink_metadata(&path).map(|m| m.file_type().is_symlink()).unwrap_or(false) {
|
||||
safe = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Ok(metadata) = fs::symlink_metadata(&path) else { continue };
|
||||
let Ok(canonical) = path.canonicalize() else { preserved += 1; continue };
|
||||
if !safe || !metadata.is_file() || !canonical.starts_with(&root) {
|
||||
preserved += 1;
|
||||
continue;
|
||||
}
|
||||
if check::state(&canonical, file, cancel) != check::State::Complete {
|
||||
preserved += 1;
|
||||
continue;
|
||||
}
|
||||
if !gate.allow(ev) {
|
||||
return Err(Stop::Failed(REPLACE_REFUSED.into()));
|
||||
}
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
log("obsolete Amazon cleanup cancelled; remaining files were preserved");
|
||||
return Ok(true);
|
||||
}
|
||||
if fs::remove_file(&canonical).is_ok() { removed += 1; } else { preserved += 1; }
|
||||
}
|
||||
log(&format!("obsolete Amazon cleanup removed={removed} preserved={preserved}"));
|
||||
Ok(cancel.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finished, Stop> {
|
||||
ev.status("Asking Amazon for the download…");
|
||||
fs::create_dir_all(&req.game_dir).map_err(|e| Stop::Failed(format!("Could not create the install folder: {e}")))?;
|
||||
@@ -156,7 +339,12 @@ fn empty_sha256() -> [u8; 32] {
|
||||
Sha256::digest(b"").into()
|
||||
}
|
||||
|
||||
pub fn run_download(req: &Request, download: &Download, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finished, Stop> {
|
||||
pub fn run_download(
|
||||
req: &Request,
|
||||
download: &Download,
|
||||
cancel: &AtomicBool,
|
||||
ev: &dyn Events,
|
||||
) -> Result<Finished, Stop> {
|
||||
let failed = Stop::Failed;
|
||||
let started = Instant::now();
|
||||
fs::create_dir_all(&req.game_dir).map_err(|e| failed(format!("Could not create the install folder: {e}")))?;
|
||||
@@ -164,7 +352,16 @@ pub fn run_download(req: &Request, download: &Download, cancel: &AtomicBool, ev:
|
||||
|
||||
ev.status("Downloading manifest…");
|
||||
let log = |line: &str| ev.log(line);
|
||||
let manifest = load_manifest(download, &req.access_token, &log).map_err(failed)?;
|
||||
let pinned_bytes = read_target_manifest(req).map_err(failed)?;
|
||||
let manifest_bytes = match pinned_bytes {
|
||||
Some(bytes) => bytes,
|
||||
None => load_manifest_bytes(download, &req.access_token, &log).map_err(failed)?,
|
||||
};
|
||||
let manifest = manifest::parse(&manifest_bytes).map_err(|e| {
|
||||
ev.log(&format!("manifest parse: {e}"));
|
||||
failed(format!("The manifest could not be read: {e}"))
|
||||
})?;
|
||||
let installed_manifest = read_installed_manifest(&req.game_dir, &log);
|
||||
cancelled(cancel)?;
|
||||
for w in &manifest.warnings {
|
||||
ev.log(w);
|
||||
@@ -216,6 +413,9 @@ pub fn run_download(req: &Request, download: &Download, cancel: &AtomicBool, ev:
|
||||
let (local, remote): (Vec<&GameFile>, Vec<&GameFile>) = pending
|
||||
.into_iter()
|
||||
.partition(|f| f.size == 0 && (f.digest.is_empty() || f.sha256() == Some(empty)));
|
||||
if remote.iter().any(|f| !f.has_supported_hash()) {
|
||||
return Err(failed(NO_VERIFIABLE_HASH.into()));
|
||||
}
|
||||
for f in &local {
|
||||
let dest = req.game_dir.join(&f.path);
|
||||
if let Some(parent) = dest.parent() {
|
||||
@@ -240,7 +440,8 @@ pub fn run_download(req: &Request, download: &Download, cancel: &AtomicBool, ev:
|
||||
path: f.path.clone(),
|
||||
dest: req.game_dir.join(&f.path),
|
||||
size: f.size,
|
||||
sha256: f.sha256(),
|
||||
algorithm: f.algorithm,
|
||||
digest: f.digest.clone(),
|
||||
url: cdn::file_url(&download.base_url, &f.cdn_name()),
|
||||
})
|
||||
.collect();
|
||||
@@ -273,10 +474,24 @@ pub fn run_download(req: &Request, download: &Download, cancel: &AtomicBool, ev:
|
||||
));
|
||||
let stats = result?;
|
||||
|
||||
let cleanup_cancelled = if let Some(installed) = installed_manifest.as_ref() {
|
||||
cleanup_obsolete(&req.game_dir, &installed.files, &manifest.files, cancel, &gate, ev, &log)?
|
||||
} else {
|
||||
ev.log("obsolete Amazon files preserved: no retained prior manifest is available");
|
||||
cancel.load(Ordering::Relaxed)
|
||||
};
|
||||
if cleanup_cancelled || cancel.load(Ordering::Relaxed) {
|
||||
return Err(Stop::Cancelled);
|
||||
}
|
||||
let _ = fs::remove_file(req.game_dir.join(IN_PROGRESS_MARKER));
|
||||
let _ = fs::File::create(req.game_dir.join(COMPLETE_MARKER));
|
||||
write_installed_manifest(&req.game_dir, &manifest_bytes).map_err(failed)?;
|
||||
Ok(Finished {
|
||||
version_id: download.version_id.clone(),
|
||||
version_id: req
|
||||
.target_version_id
|
||||
.as_deref()
|
||||
.unwrap_or(&download.version_id)
|
||||
.to_string(),
|
||||
total_bytes: total,
|
||||
file_count: manifest.files.len(),
|
||||
files_written: stats.files_written + local.len(),
|
||||
@@ -285,8 +500,12 @@ pub fn run_download(req: &Request, download: &Download, cancel: &AtomicBool, ev:
|
||||
}
|
||||
|
||||
pub fn size_of(access_token: &str, entitlement_id: &str) -> u64 {
|
||||
let Ok(download) = distribution::game_download(access_token, entitlement_id) else { return 0 };
|
||||
load_manifest(&download, access_token, &|_: &str| {}).map(|m| m.total_size()).unwrap_or(0)
|
||||
let Ok(download) = distribution::game_download(access_token, entitlement_id) else {
|
||||
return 0;
|
||||
};
|
||||
load_manifest(&download, access_token, &|_: &str| {})
|
||||
.map(|m| m.total_size())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -39,7 +39,11 @@ fn serve(files: HashMap<String, Vec<u8>>) -> Server {
|
||||
std::thread::spawn(move || answer(stream, &files, &seen));
|
||||
}
|
||||
});
|
||||
Server { base: format!("http://{addr}/v/abc?sig=s%2Bt&e=1"), seen, files }
|
||||
Server {
|
||||
base: format!("http://{addr}/v/abc?sig=s%2Bt&e=1"),
|
||||
seen,
|
||||
files,
|
||||
}
|
||||
}
|
||||
|
||||
fn answer(mut stream: TcpStream, files: &Mutex<HashMap<String, Vec<u8>>>, seen: &Mutex<Seen>) {
|
||||
@@ -136,15 +140,26 @@ fn fixture_with(paths: &[(&'static str, Vec<u8>)]) -> Fixture {
|
||||
let mut packages = vec![Vec::new(), Vec::new()];
|
||||
for (i, (path, bytes)) in paths.iter().enumerate() {
|
||||
let digest: &[u8] = if bytes.is_empty() { &[] } else { &digests[i] };
|
||||
packages[i % 2].push(Entry { path, size: bytes.len() as u64, algorithm: Some(0), digest });
|
||||
packages[i % 2].push(Entry {
|
||||
path,
|
||||
size: bytes.len() as u64,
|
||||
algorithm: Some(0),
|
||||
digest,
|
||||
});
|
||||
}
|
||||
let manifest = frame(&message(&packages), b"\x08\x01\x12\x00", true);
|
||||
let mut files = HashMap::new();
|
||||
files.insert("/v/abc/manifest.proto".to_string(), manifest);
|
||||
for (i, (_, bytes)) in paths.iter().enumerate() {
|
||||
files.insert(format!("/v/abc/files/{}", net::hex_lower(&digests[i])), bytes.clone());
|
||||
files.insert(
|
||||
format!("/v/abc/files/{}", net::hex_lower(&digests[i])),
|
||||
bytes.clone(),
|
||||
);
|
||||
}
|
||||
Fixture {
|
||||
server: serve(files),
|
||||
expected: paths.iter().map(|(p, b)| (*p, b.clone())).collect(),
|
||||
}
|
||||
Fixture { server: serve(files), expected: paths.iter().map(|(p, b)| (*p, b.clone())).collect() }
|
||||
}
|
||||
|
||||
fn fixture() -> Fixture {
|
||||
@@ -153,15 +168,38 @@ fn fixture() -> Fixture {
|
||||
("Data\\pak0.pak", pattern(2, 70_000)),
|
||||
("Data\\Sub\\readme.txt", b"hello".to_vec()),
|
||||
("Data\\empty.cfg", Vec::new()),
|
||||
("fuel.json", br#"{"Main":{"Command":"Game.exe","Args":["-w"]}}"#.to_vec()),
|
||||
(
|
||||
"fuel.json",
|
||||
br#"{"Main":{"Command":"Game.exe","Args":["-w"]}}"#.to_vec(),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn unsupported_hash_fixture() -> Fixture {
|
||||
let body = b"trusted old file".to_vec();
|
||||
let message = message(&[vec![Entry {
|
||||
path: "Game.exe",
|
||||
size: body.len() as u64,
|
||||
algorithm: Some(7),
|
||||
digest: &[1, 2],
|
||||
}]]);
|
||||
let manifest = frame(&message, b"\x08\x01\x12\x00", true);
|
||||
let mut files = HashMap::new();
|
||||
files.insert("/v/abc/manifest.proto".to_string(), manifest);
|
||||
files.insert("/v/abc/files/0102".to_string(), vec![0; body.len()]);
|
||||
Fixture {
|
||||
server: serve(files),
|
||||
expected: vec![("Game.exe", body)],
|
||||
}
|
||||
}
|
||||
|
||||
fn request(game: &Path) -> Request {
|
||||
Request {
|
||||
access_token: "token-1".into(),
|
||||
entitlement_id: "ent".into(),
|
||||
game_dir: game.to_path_buf(),
|
||||
target_manifest_path: None,
|
||||
target_version_id: None,
|
||||
max_workers: 4,
|
||||
process_workers: 2,
|
||||
ca_bundle: String::new(),
|
||||
@@ -169,7 +207,10 @@ fn request(game: &Path) -> Request {
|
||||
}
|
||||
|
||||
fn download(fx: &Fixture) -> Download {
|
||||
Download { base_url: fx.server.base.clone(), version_id: "ver-9".into() }
|
||||
Download {
|
||||
base_url: fx.server.base.clone(),
|
||||
version_id: "ver-9".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_game(name: &str) -> PathBuf {
|
||||
@@ -217,6 +258,11 @@ fn fresh_install_then_rerun_then_repair() {
|
||||
assert!(!ev.backwards.load(Ordering::SeqCst));
|
||||
assert!(game.join(COMPLETE_MARKER).exists());
|
||||
assert!(!game.join(IN_PROGRESS_MARKER).exists());
|
||||
let installed_manifest = game.join(".droiddeck-maintenance/amazon/installed.manifest");
|
||||
assert!(
|
||||
installed_manifest.is_file(),
|
||||
"the exact installed manifest is retained without CDN credentials"
|
||||
);
|
||||
assert!(no_temps(&game));
|
||||
{
|
||||
let seen = fx.server.seen.lock().unwrap();
|
||||
@@ -228,6 +274,26 @@ fn fresh_install_then_rerun_then_repair() {
|
||||
}
|
||||
|
||||
let before = requests(&fx);
|
||||
let mut pinned = request(&game);
|
||||
pinned.target_manifest_path = Some(installed_manifest.clone());
|
||||
pinned.target_version_id = Some("ver-installed".into());
|
||||
let pinned_events = Recorder::default();
|
||||
let pinned_result = run_download(&pinned, &download(&fx), &cancel, &pinned_events).unwrap();
|
||||
assert_eq!(
|
||||
pinned_result.version_id, "ver-installed",
|
||||
"repair reports the pinned installed target"
|
||||
);
|
||||
assert_eq!(
|
||||
pinned_events.gate_calls.load(Ordering::SeqCst),
|
||||
0,
|
||||
"an already-correct repair writes no files"
|
||||
);
|
||||
assert_eq!(
|
||||
requests(&fx),
|
||||
before,
|
||||
"a pinned repair uses its retained manifest and downloads no current manifest"
|
||||
);
|
||||
|
||||
let again = Recorder::default();
|
||||
run_download(&request(&game), &download(&fx), &cancel, &again).unwrap();
|
||||
assert_eq!(requests(&fx) - before, 1);
|
||||
@@ -262,7 +328,98 @@ fn a_corrupt_file_fails_the_run_and_leaves_no_temporary_files() {
|
||||
assert!(!game.join("Data/pak0.pak").exists());
|
||||
assert!(no_temps(&game));
|
||||
assert!(game.join(IN_PROGRESS_MARKER).exists());
|
||||
assert!(ev.logs.lock().unwrap().iter().any(|l| l.contains("SHA-256 mismatch")));
|
||||
assert!(ev
|
||||
.logs
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|l| l.contains("file hash mismatch")));
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obsolete_cleanup_removes_only_unchanged_prior_manifest_files() {
|
||||
let game = temp_game("obsolete-cleanup");
|
||||
fs::create_dir_all(&game).unwrap();
|
||||
fs::write(game.join("old.bin"), b"old").unwrap();
|
||||
fs::write(game.join("modified.bin"), b"user edit").unwrap();
|
||||
fs::write(game.join("untracked.bin"), b"untracked").unwrap();
|
||||
let old = vec![
|
||||
GameFile { path: "old.bin".into(), size: 3, algorithm: 0, digest: Sha256::digest(b"old").to_vec() },
|
||||
GameFile { path: "modified.bin".into(), size: 8, algorithm: 0, digest: Sha256::digest(b"original").to_vec() },
|
||||
];
|
||||
let new = vec![GameFile { path: "current.bin".into(), size: 0, algorithm: 0, digest: vec![] }];
|
||||
let cancel = AtomicBool::new(false);
|
||||
assert!(!cleanup_obsolete(&game, &old, &new, &cancel, &ReplaceGate::new(), &Recorder::default(), &|_| {}).unwrap());
|
||||
assert!(!game.join("old.bin").exists());
|
||||
assert_eq!(fs::read(game.join("modified.bin")).unwrap(), b"user edit");
|
||||
assert_eq!(fs::read(game.join("untracked.bin")).unwrap(), b"untracked");
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obsolete_cleanup_cancellation_preserves_the_old_inventory() {
|
||||
let game = temp_game("obsolete-cancel");
|
||||
fs::create_dir_all(&game).unwrap();
|
||||
fs::write(game.join("old.bin"), b"old").unwrap();
|
||||
let old = vec![GameFile { path: "old.bin".into(), size: 3, algorithm: 0, digest: Sha256::digest(b"old").to_vec() }];
|
||||
let new = vec![GameFile { path: "current.bin".into(), size: 0, algorithm: 0, digest: vec![] }];
|
||||
let cancel = AtomicBool::new(true);
|
||||
assert!(cleanup_obsolete(&game, &old, &new, &cancel, &ReplaceGate::new(), &Recorder::default(), &|_| {}).unwrap());
|
||||
assert_eq!(fs::read(game.join("old.bin")).unwrap(), b"old");
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_obsolete_cleanup_preserves_file_and_installed_manifest() {
|
||||
let fx = fixture();
|
||||
let game = temp_game("obsolete-refused");
|
||||
fs::create_dir_all(&game).unwrap();
|
||||
for (path, bytes) in &fx.expected {
|
||||
let path = game.join(path.replace('\\', "/"));
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, bytes).unwrap();
|
||||
}
|
||||
let metadata = game.join(".droiddeck-maintenance/amazon");
|
||||
fs::create_dir_all(&metadata).unwrap();
|
||||
let old_digest = Sha256::digest(b"old").to_vec();
|
||||
let old_manifest = frame(
|
||||
&message(&[vec![Entry { path: "obsolete.bin", size: 3, algorithm: Some(0), digest: &old_digest }]]),
|
||||
b"\x08\x01\x12\x00",
|
||||
true,
|
||||
);
|
||||
fs::write(game.join("obsolete.bin"), b"old").unwrap();
|
||||
fs::write(metadata.join("installed.manifest"), &old_manifest).unwrap();
|
||||
let target_manifest = fx.server.files.lock().unwrap()["/v/abc/manifest.proto"].clone();
|
||||
let target_path = metadata.join("target.manifest");
|
||||
fs::write(&target_path, target_manifest).unwrap();
|
||||
let mut req = request(&game);
|
||||
req.target_manifest_path = Some(target_path);
|
||||
req.target_version_id = Some("pinned".into());
|
||||
let cancel = AtomicBool::new(false);
|
||||
let ev = Recorder { refuse: true, ..Default::default() };
|
||||
let result = run_download(&req, &download(&fx), &cancel, &ev);
|
||||
assert_eq!(result.unwrap_err(), Stop::Failed(REPLACE_REFUSED.into()));
|
||||
assert_eq!(ev.gate_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(fs::read(game.join("obsolete.bin")).unwrap(), b"old");
|
||||
assert_eq!(fs::read(metadata.join("installed.manifest")).unwrap(), old_manifest);
|
||||
assert!(!game.join(COMPLETE_MARKER).exists());
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_hash_does_not_trust_size_or_replace_existing_content() {
|
||||
let fx = unsupported_hash_fixture();
|
||||
let game = temp_game("unsupported-hash");
|
||||
fs::create_dir_all(&game).unwrap();
|
||||
fs::write(game.join("Game.exe"), &fx.expected[0].1).unwrap();
|
||||
let cancel = AtomicBool::new(false);
|
||||
let ev = Recorder::default();
|
||||
let err = run_download(&request(&game), &download(&fx), &cancel, &ev).unwrap_err();
|
||||
assert_eq!(err, Stop::Failed(NO_VERIFIABLE_HASH.into()));
|
||||
assert_eq!(fs::read(game.join("Game.exe")).unwrap(), fx.expected[0].1);
|
||||
assert_eq!(ev.gate_calls.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(requests(&fx), 1, "only the signed manifest was requested");
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
@@ -290,14 +447,23 @@ fn cancel_and_bad_manifests() {
|
||||
|
||||
let bad = fixture_with(&[("..\\escape.dll", b"x".to_vec())]);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let err = run_download(&request(&game), &download(&bad), &cancel, &Recorder::default()).unwrap_err();
|
||||
let err = run_download(
|
||||
&request(&game),
|
||||
&download(&bad),
|
||||
&cancel,
|
||||
&Recorder::default(),
|
||||
)
|
||||
.unwrap_err();
|
||||
match err {
|
||||
Stop::Failed(m) => assert!(m.contains("..\\escape.dll"), "{m}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert!(!game.parent().unwrap().join("escape.dll").exists());
|
||||
|
||||
let missing = Download { base_url: format!("{}x", fx.server.base.split('?').next().unwrap()), version_id: String::new() };
|
||||
let missing = Download {
|
||||
base_url: format!("{}x", fx.server.base.split('?').next().unwrap()),
|
||||
version_id: String::new(),
|
||||
};
|
||||
let err = run_download(&request(&game), &missing, &cancel, &Recorder::default()).unwrap_err();
|
||||
assert_eq!(err, Stop::Failed(NO_MANIFEST.into()));
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
@@ -305,7 +471,10 @@ fn cancel_and_bad_manifests() {
|
||||
|
||||
#[test]
|
||||
fn requests_from_json() {
|
||||
let ok = Request::from_json(&json!({"accessToken":"t","entitlementId":"e","gameDir":"/g","maxWorkers":16})).unwrap();
|
||||
let ok = Request::from_json(
|
||||
&json!({"accessToken":"t","entitlementId":"e","gameDir":"/g","maxWorkers":16}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((ok.max_workers, ok.process_workers), (16, 2));
|
||||
assert!(Request::from_json(&json!({"accessToken":"t","entitlementId":"e","gameDir":"rel"})).is_err());
|
||||
assert_eq!(Request::from_json(&json!({"entitlementId":"e","gameDir":"/g"})).err().unwrap(), NOT_SIGNED_IN);
|
||||
|
||||
@@ -6,10 +6,16 @@ use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use sha3::{
|
||||
digest::{ExtendableOutput, Update, XofReader},
|
||||
Shake128,
|
||||
};
|
||||
|
||||
use super::check::temp_path;
|
||||
use super::{Events, ReplaceGate, Stop};
|
||||
use crate::fetch_core::{distinct_host_count, run_fetch, FetchItem, FetchOptions, FetchSink, SinkError};
|
||||
use crate::fetch_core::{
|
||||
distinct_host_count, run_fetch, FetchItem, FetchOptions, FetchSink, SinkError,
|
||||
};
|
||||
|
||||
const PROGRESS_EVERY_MS: u64 = 50;
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
@@ -18,10 +24,44 @@ pub struct Job {
|
||||
pub path: String,
|
||||
pub dest: PathBuf,
|
||||
pub size: u64,
|
||||
pub sha256: Option<[u8; 32]>,
|
||||
pub algorithm: u64,
|
||||
pub digest: Vec<u8>,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
enum HashState {
|
||||
Sha256(Sha256),
|
||||
Shake128(Shake128),
|
||||
}
|
||||
|
||||
impl HashState {
|
||||
fn for_algorithm(algorithm: u64) -> Self {
|
||||
match algorithm {
|
||||
1 => Self::Shake128(Shake128::default()),
|
||||
_ => Self::Sha256(Sha256::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, data: &[u8]) {
|
||||
match self {
|
||||
Self::Sha256(h) => Digest::update(h, data),
|
||||
Self::Shake128(h) => Update::update(h, data),
|
||||
}
|
||||
}
|
||||
|
||||
fn matches(self, digest: &[u8]) -> bool {
|
||||
match self {
|
||||
Self::Sha256(h) => h.finalize().as_slice() == digest,
|
||||
Self::Shake128(h) => {
|
||||
let mut reader = h.finalize_xof();
|
||||
let mut got = vec![0; digest.len()];
|
||||
reader.read(&mut got);
|
||||
got == digest
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Settings {
|
||||
pub max_workers: usize,
|
||||
pub process_workers: usize,
|
||||
@@ -47,7 +87,7 @@ pub struct Stats {
|
||||
struct Active {
|
||||
file: File,
|
||||
tmp: PathBuf,
|
||||
hasher: Sha256,
|
||||
hasher: HashState,
|
||||
written: u64,
|
||||
}
|
||||
|
||||
@@ -113,7 +153,12 @@ impl Placer<'_> {
|
||||
}
|
||||
let tmp = temp_path(&job.dest);
|
||||
let file = File::create(&tmp).map_err(|e| format!("Could not write {}: {e}", job.path))?;
|
||||
Ok(Active { file, tmp, hasher: Sha256::new(), written: 0 })
|
||||
Ok(Active {
|
||||
file,
|
||||
tmp,
|
||||
hasher: HashState::for_algorithm(job.algorithm),
|
||||
written: 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn piece(&self, i: usize, offset: u64, data: &[u8]) -> Result<(), SinkError> {
|
||||
@@ -124,7 +169,10 @@ impl Placer<'_> {
|
||||
self.in_flight.fetch_sub(old.written, Ordering::Relaxed);
|
||||
discard(old);
|
||||
}
|
||||
*slot = Some(self.start(job).map_err(|e| SinkError::Fatal(self.fail(e)))?);
|
||||
*slot = Some(
|
||||
self.start(job)
|
||||
.map_err(|e| SinkError::Fatal(self.fail(e)))?,
|
||||
);
|
||||
}
|
||||
let Some(active) = slot.as_mut() else {
|
||||
return Err(SinkError::Retry(format!("{}: data arrived before the start of the file", job.path)));
|
||||
@@ -135,10 +183,9 @@ impl Placer<'_> {
|
||||
if active.written + data.len() as u64 > job.size {
|
||||
return Err(SinkError::Retry(format!("{}: the CDN sent more than the manifest size", job.path)));
|
||||
}
|
||||
active
|
||||
.file
|
||||
.write_all(data)
|
||||
.map_err(|e| SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path))))?;
|
||||
active.file.write_all(data).map_err(|e| {
|
||||
SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path)))
|
||||
})?;
|
||||
active.hasher.update(data);
|
||||
active.written += data.len() as u64;
|
||||
self.in_flight.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
@@ -161,19 +208,23 @@ impl Placer<'_> {
|
||||
discard(active);
|
||||
return Err(SinkError::Retry(format!("{}: {got} bytes arrived, the manifest says {}", job.path, job.size)));
|
||||
}
|
||||
let Active { file, tmp, hasher, .. } = active;
|
||||
if let Some(expected) = job.sha256 {
|
||||
let got: [u8; 32] = hasher.finalize().into();
|
||||
if got != expected {
|
||||
drop(file);
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(SinkError::Retry(format!("{}: SHA-256 mismatch", job.path)));
|
||||
}
|
||||
let Active {
|
||||
file, tmp, hasher, ..
|
||||
} = active;
|
||||
if !hasher.matches(&job.digest) {
|
||||
drop(file);
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(SinkError::Retry(format!(
|
||||
"{}: file hash mismatch",
|
||||
job.path
|
||||
)));
|
||||
}
|
||||
if let Err(e) = file.sync_all() {
|
||||
drop(file);
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path))));
|
||||
return Err(SinkError::Fatal(
|
||||
self.fail(format!("Could not write {}: {e}", job.path)),
|
||||
));
|
||||
}
|
||||
drop(file);
|
||||
if self.stop.load(Ordering::SeqCst) {
|
||||
@@ -186,7 +237,9 @@ impl Placer<'_> {
|
||||
}
|
||||
if let Err(e) = fs::rename(&tmp, &job.dest) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(SinkError::Fatal(self.fail(format!("Could not put {} in place: {e}", job.path))));
|
||||
return Err(SinkError::Fatal(
|
||||
self.fail(format!("Could not put {} in place: {e}", job.path)),
|
||||
));
|
||||
}
|
||||
self.placed[i].store(true, Ordering::SeqCst);
|
||||
self.placed_bytes.fetch_add(job.size, Ordering::Relaxed);
|
||||
@@ -213,11 +266,23 @@ impl FetchSink for Sink<'_, '_> {
|
||||
}
|
||||
|
||||
pub fn worker_counts(max_workers: usize, process_workers: usize) -> (usize, usize) {
|
||||
let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(2);
|
||||
(max_workers.clamp(1, 128), process_workers.max(cores / 2).max(1))
|
||||
let cores = std::thread::available_parallelism()
|
||||
.map(|n| n.get())
|
||||
.unwrap_or(2);
|
||||
(
|
||||
max_workers.clamp(1, 128),
|
||||
process_workers.max(cores / 2).max(1),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn run(jobs: &[Job], settings: &Settings, base: Baseline, gate: &ReplaceGate, stop: &AtomicBool, events: &dyn Events) -> Result<Stats, Stop> {
|
||||
pub fn run(
|
||||
jobs: &[Job],
|
||||
settings: &Settings,
|
||||
base: Baseline,
|
||||
gate: &ReplaceGate,
|
||||
stop: &AtomicBool,
|
||||
events: &dyn Events,
|
||||
) -> Result<Stats, Stop> {
|
||||
let placer = Placer {
|
||||
jobs,
|
||||
slots: jobs.iter().map(|_| Mutex::new(None)).collect(),
|
||||
@@ -250,7 +315,12 @@ pub fn run(jobs: &[Job], settings: &Settings, base: Baseline, gate: &ReplaceGate
|
||||
let items: Vec<FetchItem> = jobs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, j)| FetchItem { id: i as u64, urls: vec![j.url.clone()], reserve: j.size, range: None })
|
||||
.map(|(i, j)| FetchItem {
|
||||
id: i as u64,
|
||||
urls: vec![j.url.clone()],
|
||||
reserve: j.size,
|
||||
range: None,
|
||||
})
|
||||
.collect();
|
||||
events.log(&format!(
|
||||
"engine files={} window={window} process_workers={process} per_host_cap={} hosts={}",
|
||||
@@ -263,7 +333,15 @@ pub fn run(jobs: &[Job], settings: &Settings, base: Baseline, gate: &ReplaceGate
|
||||
let outcome = if items.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(run_fetch(items, &settings.hosts, &options, &Sink(&placer), stop, &|_: u64, _: u64| {}, &log))
|
||||
Some(run_fetch(
|
||||
items,
|
||||
&settings.hosts,
|
||||
&options,
|
||||
&Sink(&placer),
|
||||
stop,
|
||||
&|_: u64, _: u64| {},
|
||||
&log,
|
||||
))
|
||||
};
|
||||
|
||||
for slot in &placer.slots {
|
||||
@@ -299,5 +377,7 @@ pub fn run(jobs: &[Job], settings: &Settings, base: Baseline, gate: &ReplaceGate
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
return Err(Stop::Cancelled);
|
||||
}
|
||||
Err(Stop::Failed("The download ended before every file was written".into()))
|
||||
Err(Stop::Failed(
|
||||
"The download ended before every file was written".into(),
|
||||
))
|
||||
}
|
||||
@@ -5,6 +5,7 @@ use super::net::hex_lower;
|
||||
use super::proto::{Fields, Value};
|
||||
|
||||
pub const SHA256_ALGORITHM: u64 = 0;
|
||||
pub const SHAKE128_ALGORITHM: u64 = 1;
|
||||
|
||||
pub const RESERVED_ROOT_NAMES: &[&str] = &[
|
||||
".droiddeck-store.json",
|
||||
@@ -12,6 +13,7 @@ pub const RESERVED_ROOT_NAMES: &[&str] = &[
|
||||
".droiddeck-launch.bat",
|
||||
".amazon_download_in_progress",
|
||||
".amazon_download_complete",
|
||||
".droiddeck-maintenance",
|
||||
];
|
||||
|
||||
pub const TEMP_SUFFIX: &str = ".tmp";
|
||||
@@ -33,6 +35,14 @@ impl GameFile {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_supported_hash(&self) -> bool {
|
||||
match self.algorithm {
|
||||
SHA256_ALGORITHM => self.digest.len() == 32,
|
||||
SHAKE128_ALGORITHM => !self.digest.is_empty(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cdn_name(&self) -> String {
|
||||
hex_lower(&self.digest)
|
||||
}
|
||||
@@ -70,6 +80,13 @@ pub fn check_path(raw: &str) -> Result<String, String> {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if path
|
||||
.split('/')
|
||||
.next()
|
||||
.is_some_and(|first| first.eq_ignore_ascii_case(".droiddeck-maintenance"))
|
||||
{
|
||||
return refuse("DroidDeck's own metadata");
|
||||
}
|
||||
if !path.contains('/') && RESERVED_ROOT_NAMES.iter().any(|r| r.eq_ignore_ascii_case(&path)) {
|
||||
return refuse("DroidDeck's own file");
|
||||
}
|
||||
@@ -118,7 +135,12 @@ fn parse_file(data: &[u8]) -> Result<Option<GameFile>, String> {
|
||||
if algorithm == SHA256_ALGORITHM && !digest.is_empty() && digest.len() != 32 {
|
||||
return Err(format!("The manifest has a {}-byte SHA-256 for {path}", digest.len()));
|
||||
}
|
||||
Ok(Some(GameFile { path, size, algorithm, digest }))
|
||||
Ok(Some(GameFile {
|
||||
path,
|
||||
size,
|
||||
algorithm,
|
||||
digest,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn parse_message(data: &[u8]) -> Result<Manifest, String> {
|
||||
@@ -138,7 +160,9 @@ pub fn parse_message(data: &[u8]) -> Result<Manifest, String> {
|
||||
(2, _) => return Err("file field has the wrong type".into()),
|
||||
_ => continue,
|
||||
};
|
||||
let Some(file) = parse_file(entry)? else { continue };
|
||||
let Some(file) = parse_file(entry)? else {
|
||||
continue;
|
||||
};
|
||||
out.entries += 1;
|
||||
match index.get(&file.path) {
|
||||
Some(&i) => {
|
||||
@@ -219,10 +243,25 @@ mod tests {
|
||||
let d2: Vec<u8> = Sha256::digest(b"two").to_vec();
|
||||
let msg = message(&[
|
||||
vec![
|
||||
Entry { path: "Binaries\\Win64\\Game.exe", size: 3, algorithm: Some(0), digest: &d1 },
|
||||
Entry { path: "", size: 9, algorithm: None, digest: &d1 },
|
||||
Entry {
|
||||
path: "Binaries\\Win64\\Game.exe",
|
||||
size: 3,
|
||||
algorithm: Some(0),
|
||||
digest: &d1,
|
||||
},
|
||||
Entry {
|
||||
path: "",
|
||||
size: 9,
|
||||
algorithm: None,
|
||||
digest: &d1,
|
||||
},
|
||||
],
|
||||
vec![Entry { path: "fuel.json", size: 3, algorithm: None, digest: &d2 }],
|
||||
vec![Entry {
|
||||
path: "fuel.json",
|
||||
size: 3,
|
||||
algorithm: None,
|
||||
digest: &d2,
|
||||
}],
|
||||
]);
|
||||
for xz in [true, false] {
|
||||
let m = parse(&frame(&msg, b"\x0a\x00", xz)).unwrap();
|
||||
@@ -238,7 +277,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn other_algorithms_are_not_verified_but_still_named() {
|
||||
let msg = message(&[vec![Entry { path: "a", size: 1, algorithm: Some(7), digest: &[0xab, 0xcd] }]]);
|
||||
let msg = message(&[vec![Entry {
|
||||
path: "a",
|
||||
size: 1,
|
||||
algorithm: Some(7),
|
||||
digest: &[0xab, 0xcd],
|
||||
}]]);
|
||||
let m = parse_message(&msg).unwrap();
|
||||
assert_eq!(m.files[0].sha256(), None);
|
||||
assert_eq!(m.files[0].cdn_name(), "abcd");
|
||||
@@ -249,8 +293,18 @@ mod tests {
|
||||
let a = [1u8; 32];
|
||||
let b = [2u8; 32];
|
||||
let msg = message(&[vec![
|
||||
Entry { path: "x\\y.bin", size: 1, algorithm: Some(0), digest: &a },
|
||||
Entry { path: "x/y.bin", size: 2, algorithm: Some(0), digest: &b },
|
||||
Entry {
|
||||
path: "x\\y.bin",
|
||||
size: 1,
|
||||
algorithm: Some(0),
|
||||
digest: &a,
|
||||
},
|
||||
Entry {
|
||||
path: "x/y.bin",
|
||||
size: 2,
|
||||
algorithm: Some(0),
|
||||
digest: &b,
|
||||
},
|
||||
]]);
|
||||
let m = parse_message(&msg).unwrap();
|
||||
assert_eq!(m.files.len(), 1);
|
||||
@@ -273,9 +327,16 @@ mod tests {
|
||||
".droiddeck-store.json",
|
||||
".DroidDeck-Launch.BAT",
|
||||
".amazon_download_complete",
|
||||
".droiddeck-maintenance/operation.json",
|
||||
".DROIDDECK-MAINTENANCE/amazon/installed.manifest",
|
||||
] {
|
||||
assert!(check_path(bad).is_err(), "{bad}");
|
||||
let msg = message(&[vec![Entry { path: bad, size: 1, algorithm: Some(0), digest: &[0; 32] }]]);
|
||||
let msg = message(&[vec![Entry {
|
||||
path: bad,
|
||||
size: 1,
|
||||
algorithm: Some(0),
|
||||
digest: &[0; 32],
|
||||
}]]);
|
||||
let err = parse_message(&msg).unwrap_err();
|
||||
assert!(err.contains(bad), "{err}");
|
||||
}
|
||||
@@ -285,18 +346,48 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn malformed_entries_are_errors() {
|
||||
let no_hash = message(&[vec![Entry { path: "a", size: 5, algorithm: Some(0), digest: &[] }]]);
|
||||
let no_hash = message(&[vec![Entry {
|
||||
path: "a",
|
||||
size: 5,
|
||||
algorithm: Some(0),
|
||||
digest: &[],
|
||||
}]]);
|
||||
assert!(parse_message(&no_hash).is_err());
|
||||
let empty_ok = message(&[vec![Entry { path: "e", size: 0, algorithm: Some(0), digest: &[] }]]);
|
||||
let empty_ok = message(&[vec![Entry {
|
||||
path: "e",
|
||||
size: 0,
|
||||
algorithm: Some(0),
|
||||
digest: &[],
|
||||
}]]);
|
||||
assert_eq!(parse_message(&empty_ok).unwrap().files[0].sha256(), None);
|
||||
let short = message(&[vec![Entry { path: "a", size: 5, algorithm: Some(0), digest: &[1, 2] }]]);
|
||||
let short = message(&[vec![Entry {
|
||||
path: "a",
|
||||
size: 5,
|
||||
algorithm: Some(0),
|
||||
digest: &[1, 2],
|
||||
}]]);
|
||||
assert!(parse_message(&short).is_err());
|
||||
let clash = message(&[vec![
|
||||
Entry { path: "a.bin", size: 1, algorithm: Some(0), digest: &[1; 32] },
|
||||
Entry { path: "a.bin.tmp", size: 1, algorithm: Some(0), digest: &[2; 32] },
|
||||
Entry {
|
||||
path: "a.bin",
|
||||
size: 1,
|
||||
algorithm: Some(0),
|
||||
digest: &[1; 32],
|
||||
},
|
||||
Entry {
|
||||
path: "a.bin.tmp",
|
||||
size: 1,
|
||||
algorithm: Some(0),
|
||||
digest: &[2; 32],
|
||||
},
|
||||
]]);
|
||||
assert!(parse_message(&clash).is_err());
|
||||
let mut truncated = message(&[vec![Entry { path: "a", size: 1, algorithm: Some(0), digest: &[1; 32] }]]);
|
||||
let mut truncated = message(&[vec![Entry {
|
||||
path: "a",
|
||||
size: 1,
|
||||
algorithm: Some(0),
|
||||
digest: &[1; 32],
|
||||
}]]);
|
||||
truncated.truncate(truncated.len() - 3);
|
||||
assert!(parse_message(&truncated).is_err());
|
||||
assert!(parse_message(&[0x08, 0x01]).is_err());
|
||||
|
||||
@@ -65,14 +65,18 @@ fn dispatch(op: &str, req: &Value) -> Value {
|
||||
let games = library::visible(all);
|
||||
json!({ "total": total, "games": games.iter().map(library::Game::to_json).collect::<Vec<_>>() })
|
||||
}
|
||||
Err(Failure::SignIn) => json!({ "error": "Amazon refused the session", "signIn": true }),
|
||||
Err(Failure::SignIn) => {
|
||||
json!({ "error": "Amazon refused the session", "signIn": true })
|
||||
}
|
||||
Err(Failure::Other(e)) => error(e),
|
||||
},
|
||||
"download.lookup" => match distribution::game_download(token, str_of(req, "entitlementId")) {
|
||||
Ok(d) => json!({ "downloadUrl": d.base_url, "versionId": d.version_id }),
|
||||
Err(f) => error(f.message()),
|
||||
},
|
||||
"download.size" => json!({ "bytes": install::size_of(token, str_of(req, "entitlementId")) }),
|
||||
"download.size" => {
|
||||
json!({ "bytes": install::size_of(token, str_of(req, "entitlementId")) })
|
||||
}
|
||||
"launch.spec" => {
|
||||
let dir = str_of(req, "gameDir");
|
||||
if dir.is_empty() {
|
||||
@@ -82,7 +86,11 @@ fn dispatch(op: &str, req: &Value) -> Value {
|
||||
json!({ "exe": spec.exe, "args": spec.args, "source": spec.source, "warning": spec.warning })
|
||||
}
|
||||
"launch.env" => {
|
||||
let env = launch::fuel_environment(str_of(req, "entitlementId"), str_of(req, "sku"), str_of(req, "displayName"));
|
||||
let env = launch::fuel_environment(
|
||||
str_of(req, "entitlementId"),
|
||||
str_of(req, "sku"),
|
||||
str_of(req, "displayName"),
|
||||
);
|
||||
json!({ "env": env.iter().map(|(k, v)| json!([k, v])).collect::<Vec<_>>() })
|
||||
}
|
||||
_ => error(format!("unknown operation {op}")),
|
||||
@@ -105,7 +113,11 @@ pub fn fetch(op: &str, request: &str) -> Option<Vec<u8>> {
|
||||
|
||||
pub fn inspect(bytes: &[u8], _request: &str) -> String {
|
||||
match manifest::parse(bytes) {
|
||||
Ok(m) => json!({ "totalBytes": m.total_size(), "files": m.files.len() }).to_string(),
|
||||
Ok(m) => json!({
|
||||
"totalBytes": m.total_size(),
|
||||
"files": m.files.len(),
|
||||
"unverifiableFiles": m.files.iter().filter(|f| !f.has_supported_hash() && !(f.size == 0 && f.digest.is_empty())).count(),
|
||||
}).to_string(),
|
||||
Err(e) => error(e).to_string(),
|
||||
}
|
||||
}
|
||||
@@ -123,12 +135,23 @@ mod tests {
|
||||
assert_eq!(v["redirectMarker"], "openid.oa2.authorization_code=");
|
||||
assert!(v["userAgent"].as_str().unwrap().contains("Firefox"));
|
||||
assert_eq!(v["serial"].as_str().unwrap().len(), 32);
|
||||
let v: Value = serde_json::from_str(&call("auth.register", r#"{"url":"https://www.amazon.com/?a=1"}"#)).unwrap();
|
||||
let v: Value = serde_json::from_str(&call(
|
||||
"auth.register",
|
||||
r#"{"url":"https://www.amazon.com/?a=1"}"#,
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(v["noCode"], true);
|
||||
let v: Value = serde_json::from_str(&call("auth.register", r#"{"code":"c"}"#)).unwrap();
|
||||
assert!(v["error"].is_string() && v.get("noCode").is_none());
|
||||
let v: Value = serde_json::from_str(&call("launch.env", r#"{"entitlementId":"e","sku":"s","displayName":""}"#)).unwrap();
|
||||
assert_eq!(v["env"][2], json!(["AMAZON_GAMES_FUEL_ENTITLEMENT_ID", "e"]));
|
||||
let v: Value = serde_json::from_str(&call(
|
||||
"launch.env",
|
||||
r#"{"entitlementId":"e","sku":"s","displayName":""}"#,
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
v["env"][2],
|
||||
json!(["AMAZON_GAMES_FUEL_ENTITLEMENT_ID", "e"])
|
||||
);
|
||||
assert_eq!(v["env"][4][1], "Player");
|
||||
let v: Value = serde_json::from_str(&call("nope", "{}")).unwrap();
|
||||
assert!(v["error"].is_string());
|
||||
@@ -138,13 +161,36 @@ mod tests {
|
||||
#[test]
|
||||
fn inspect_sizes() {
|
||||
let msg = message(&[vec![
|
||||
Entry { path: "a", size: 10, algorithm: Some(0), digest: &[1; 32] },
|
||||
Entry { path: "b\\c", size: 5, algorithm: Some(0), digest: &[2; 32] },
|
||||
Entry {
|
||||
path: "a",
|
||||
size: 10,
|
||||
algorithm: Some(0),
|
||||
digest: &[1; 32],
|
||||
},
|
||||
Entry {
|
||||
path: "b\\c",
|
||||
size: 5,
|
||||
algorithm: Some(0),
|
||||
digest: &[2; 32],
|
||||
},
|
||||
]]);
|
||||
let v: Value = serde_json::from_str(&inspect(&frame(&msg, b"", true), "{}")).unwrap();
|
||||
assert_eq!(v["totalBytes"], 15);
|
||||
assert_eq!(v["files"], 2);
|
||||
assert_eq!(v["unverifiableFiles"], 0);
|
||||
let v: Value = serde_json::from_str(&inspect(b"xx", "{}")).unwrap();
|
||||
assert!(v["error"].is_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_reports_unsupported_file_hashes() {
|
||||
let msg = message(&[vec![Entry {
|
||||
path: "a",
|
||||
size: 2,
|
||||
algorithm: Some(7),
|
||||
digest: &[1, 2],
|
||||
}]]);
|
||||
let v: Value = serde_json::from_str(&inspect(&frame(&msg, b"", true), "{}")).unwrap();
|
||||
assert_eq!(v["unverifiableFiles"], 1);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
use crate::epic::manifest::{guid_from_hex, guid_text, ChunkInfo};
|
||||
use crate::epic::manifest::{guid_from_hex, guid_text, ChunkInfo, Manifest};
|
||||
|
||||
pub fn entry_name(chunk: &ChunkInfo, copy: u32) -> String {
|
||||
if copy == 0 {
|
||||
@@ -85,7 +86,9 @@ pub fn prepare(
|
||||
let mut candidates: Vec<(u32, u32, PathBuf)> = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let Ok(meta) = fs::symlink_metadata(&path) else { continue };
|
||||
let Ok(meta) = fs::symlink_metadata(&path) else {
|
||||
continue;
|
||||
};
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let chunk = by_name.get(&name).copied().filter(|_| name.len() == 32 && guid_from_hex(&name).is_some());
|
||||
let usable = meta.is_file() && !meta.file_type().is_symlink();
|
||||
@@ -128,10 +131,234 @@ pub fn prepare(
|
||||
kept
|
||||
}
|
||||
|
||||
struct Rebuilt {
|
||||
bytes: Vec<u8>,
|
||||
covered: Vec<bool>,
|
||||
uncovered: usize,
|
||||
valid: bool,
|
||||
}
|
||||
|
||||
pub fn seed_from_verified_installed(
|
||||
dir: &Path,
|
||||
game_dir: &Path,
|
||||
installed: &Manifest,
|
||||
target: &Manifest,
|
||||
needed: &HashSet<u32>,
|
||||
cached: &[u32],
|
||||
budget: u64,
|
||||
cancel: &AtomicBool,
|
||||
) -> (Vec<u32>, u64) {
|
||||
seed_from_verified_installed_with_check(
|
||||
dir, game_dir, installed, target, needed, cached, budget, cancel, super::delta::check,
|
||||
)
|
||||
}
|
||||
|
||||
fn seed_from_verified_installed_with_check<F>(
|
||||
dir: &Path,
|
||||
game_dir: &Path,
|
||||
installed: &Manifest,
|
||||
target: &Manifest,
|
||||
needed: &HashSet<u32>,
|
||||
cached: &[u32],
|
||||
budget: u64,
|
||||
cancel: &AtomicBool,
|
||||
mut check: F,
|
||||
) -> (Vec<u32>, u64)
|
||||
where
|
||||
F: FnMut(&Path, u64, Option<[u8; 20]>, &AtomicBool) -> super::delta::Check,
|
||||
{
|
||||
const MAX_WINDOW: u32 = 64 * 1024 * 1024;
|
||||
const MAX_REBUILD_MEMORY: u64 = 32 * 1024 * 1024;
|
||||
let cached: HashSet<u32> = cached.iter().copied().collect();
|
||||
let mut rebuilt: HashMap<u32, Rebuilt> = HashMap::new();
|
||||
let mut reserved = 0u64;
|
||||
let budget = budget.min(MAX_REBUILD_MEMORY);
|
||||
let wanted = needed
|
||||
.iter()
|
||||
.filter(|index| !cached.contains(index) && target.chunks.get(**index as usize).is_some())
|
||||
.count();
|
||||
for file in &installed.files {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if !rebuilt.is_empty()
|
||||
&& rebuilt.values().all(|chunk| !chunk.valid || chunk.uncovered == 0)
|
||||
&& (reserved >= budget || rebuilt.len() >= wanted)
|
||||
{
|
||||
break;
|
||||
}
|
||||
let Some(expected) = file.sha1 else { continue };
|
||||
if !super::safe_relative(&file.path) {
|
||||
continue;
|
||||
}
|
||||
let useful = file.parts.iter().any(|part| {
|
||||
if part.size == 0 {
|
||||
return false;
|
||||
}
|
||||
let Some(&target_index) = target.chunk_index.get(&part.guid) else {
|
||||
return false;
|
||||
};
|
||||
let target_index = target_index as u32;
|
||||
if !needed.contains(&target_index) || cached.contains(&target_index) {
|
||||
return false;
|
||||
}
|
||||
let Some(info) = target.chunks.get(target_index as usize) else {
|
||||
return false;
|
||||
};
|
||||
if !info.window_exact
|
||||
|| info.window > MAX_WINDOW
|
||||
|| part.offset.saturating_add(part.size) > info.window
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(chunk) = rebuilt.get(&target_index) {
|
||||
let start = part.offset as usize;
|
||||
let end = start + part.size as usize;
|
||||
chunk.valid && chunk.covered[start..end].iter().any(|present| !present)
|
||||
} else {
|
||||
reserved.saturating_add(info.window as u64) <= budget
|
||||
}
|
||||
});
|
||||
if !useful {
|
||||
continue;
|
||||
}
|
||||
let path = game_dir.join(&file.path);
|
||||
let mut safe = game_dir.to_path_buf();
|
||||
let mut no_links = true;
|
||||
for segment in file.path.split('/') {
|
||||
safe.push(segment);
|
||||
if fs::symlink_metadata(&safe)
|
||||
.map(|m| m.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
no_links = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !no_links {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = fs::symlink_metadata(&path) else {
|
||||
continue;
|
||||
};
|
||||
if !meta.is_file() || meta.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
match check(&path, file.size, Some(expected), cancel) {
|
||||
super::delta::Check::Cancelled => break,
|
||||
super::delta::Check::UpToDate => {}
|
||||
super::delta::Check::Pending { .. } => continue,
|
||||
}
|
||||
let mut source = match fs::File::open(&path) {
|
||||
Ok(f) => f,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let mut file_offset = 0u64;
|
||||
for part in &file.parts {
|
||||
let Some(&target_index) = target.chunk_index.get(&part.guid) else {
|
||||
file_offset += part.size as u64;
|
||||
continue;
|
||||
};
|
||||
let target_index = target_index as u32;
|
||||
if !needed.contains(&target_index) || cached.contains(&target_index) {
|
||||
file_offset += part.size as u64;
|
||||
continue;
|
||||
}
|
||||
let info = &target.chunks[target_index as usize];
|
||||
if !info.window_exact
|
||||
|| info.window > MAX_WINDOW
|
||||
|| part.offset.saturating_add(part.size) > info.window
|
||||
{
|
||||
file_offset += part.size as u64;
|
||||
continue;
|
||||
}
|
||||
if !rebuilt.contains_key(&target_index) {
|
||||
let size = info.window as u64;
|
||||
if reserved.saturating_add(size) > budget {
|
||||
file_offset += part.size as u64;
|
||||
continue;
|
||||
}
|
||||
reserved += size;
|
||||
rebuilt.insert(
|
||||
target_index,
|
||||
Rebuilt {
|
||||
bytes: vec![0; info.window as usize],
|
||||
covered: vec![false; info.window as usize],
|
||||
uncovered: info.window as usize,
|
||||
valid: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
let Some(chunk) = rebuilt.get_mut(&target_index) else {
|
||||
file_offset += part.size as u64;
|
||||
continue;
|
||||
};
|
||||
if file_offset.saturating_add(part.size as u64) > file.size {
|
||||
chunk.valid = false;
|
||||
file_offset += part.size as u64;
|
||||
continue;
|
||||
}
|
||||
let mut data = vec![0; part.size as usize];
|
||||
if source.seek(SeekFrom::Start(file_offset)).is_err()
|
||||
|| source.read_exact(&mut data).is_err()
|
||||
{
|
||||
chunk.valid = false;
|
||||
file_offset += part.size as u64;
|
||||
continue;
|
||||
}
|
||||
for (n, byte) in data.into_iter().enumerate() {
|
||||
let at = part.offset as usize + n;
|
||||
if chunk.covered[at] && chunk.bytes[at] != byte {
|
||||
chunk.valid = false;
|
||||
break;
|
||||
}
|
||||
if !chunk.covered[at] {
|
||||
chunk.uncovered -= 1;
|
||||
}
|
||||
chunk.bytes[at] = byte;
|
||||
chunk.covered[at] = true;
|
||||
}
|
||||
file_offset += part.size as u64;
|
||||
}
|
||||
}
|
||||
|
||||
let mut seeded = Vec::new();
|
||||
let mut bytes_written = 0u64;
|
||||
for (index, chunk) in rebuilt {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if !chunk.valid || chunk.uncovered != 0 {
|
||||
continue;
|
||||
}
|
||||
if target.chunks[index as usize]
|
||||
.sha1
|
||||
.is_some_and(|expected| <[u8; 20]>::from(Sha1::digest(&chunk.bytes)) != expected)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if store(
|
||||
dir,
|
||||
&guid_text(&target.chunks[index as usize].guid),
|
||||
&chunk.bytes,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
bytes_written += chunk.bytes.len() as u64;
|
||||
seeded.push(index);
|
||||
}
|
||||
}
|
||||
(seeded, bytes_written)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::epic::manifest::testing::chunk;
|
||||
use crate::epic::manifest::{
|
||||
testing::{build, chunk, TestFile, TestManifest},
|
||||
PartRef,
|
||||
};
|
||||
use sha1::Digest;
|
||||
|
||||
#[test]
|
||||
fn keeps_only_valid_needed_entries_within_budget() {
|
||||
@@ -159,4 +386,169 @@ mod tests {
|
||||
assert_eq!(left, want);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconstructs_needed_chunks_only_from_sha1_verified_installed_files() {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("dd-epic-installed-chunks-{}", std::process::id()));
|
||||
let game = root.join("game");
|
||||
let cache = root.join("cache");
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
fs::create_dir_all(&game).unwrap();
|
||||
let info = chunk(41, 4);
|
||||
let make = || TestManifest {
|
||||
version: 21,
|
||||
build: "installed".into(),
|
||||
exe: "Game.exe".into(),
|
||||
prereq: None,
|
||||
chunks: vec![info.clone()],
|
||||
files: vec![TestFile {
|
||||
path: "source.bin".into(),
|
||||
sha1: Sha1::digest(b"abcd").into(),
|
||||
tags: Vec::new(),
|
||||
parts: vec![PartRef {
|
||||
guid: info.guid,
|
||||
offset: 0,
|
||||
size: 4,
|
||||
}],
|
||||
}],
|
||||
compress: false,
|
||||
meta_tail: Vec::new(),
|
||||
};
|
||||
let installed = crate::epic::manifest::parse(&build(&make())).unwrap();
|
||||
let target = crate::epic::manifest::parse(&build(&make())).unwrap();
|
||||
fs::write(game.join("source.bin"), b"abcd").unwrap();
|
||||
let cancel = AtomicBool::new(false);
|
||||
let needed = HashSet::from([0]);
|
||||
let (seeded, written) = seed_from_verified_installed(
|
||||
&cache,
|
||||
&game,
|
||||
&installed,
|
||||
&target,
|
||||
&needed,
|
||||
&[],
|
||||
4,
|
||||
&cancel,
|
||||
);
|
||||
assert_eq!(seeded, vec![0]);
|
||||
assert_eq!(written, 4);
|
||||
assert_eq!(
|
||||
fs::read(cache.join(guid_text(&info.guid))).unwrap(),
|
||||
b"abcd"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(&cache).unwrap();
|
||||
fs::write(game.join("source.bin"), b"abXd").unwrap();
|
||||
let (seeded, written) = seed_from_verified_installed(
|
||||
&cache,
|
||||
&game,
|
||||
&installed,
|
||||
&target,
|
||||
&needed,
|
||||
&[],
|
||||
4,
|
||||
&cancel,
|
||||
);
|
||||
assert!(seeded.is_empty());
|
||||
assert_eq!(written, 0);
|
||||
assert!(!cache.join(guid_text(&info.guid)).exists());
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_verified_installed_files_that_cannot_seed_needed_chunks() {
|
||||
let root = std::env::temp_dir().join(format!("dd-epic-cache-filter-{}", std::process::id()));
|
||||
let game = root.join("game");
|
||||
let cache = root.join("cache");
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
fs::create_dir_all(&game).unwrap();
|
||||
let needed_chunk = chunk(51, 4);
|
||||
let second_needed_chunk = chunk(52, 4);
|
||||
let unrelated_chunk = chunk(53, 4);
|
||||
let installed_bytes = build(&TestManifest {
|
||||
version: 21,
|
||||
build: "installed".into(),
|
||||
exe: "Game.exe".into(),
|
||||
prereq: None,
|
||||
chunks: vec![needed_chunk.clone(), unrelated_chunk.clone()],
|
||||
files: vec![
|
||||
TestFile {
|
||||
path: "source.bin".into(),
|
||||
sha1: Sha1::digest(b"abcd").into(),
|
||||
tags: Vec::new(),
|
||||
parts: vec![PartRef { guid: needed_chunk.guid, offset: 0, size: 4 }],
|
||||
},
|
||||
TestFile {
|
||||
path: "irrelevant.bin".into(),
|
||||
sha1: Sha1::digest(b"wxyz").into(),
|
||||
tags: Vec::new(),
|
||||
parts: vec![PartRef { guid: unrelated_chunk.guid, offset: 0, size: 4 }],
|
||||
},
|
||||
TestFile {
|
||||
path: "second-source.bin".into(),
|
||||
sha1: Sha1::digest(b"efgh").into(),
|
||||
tags: Vec::new(),
|
||||
parts: vec![PartRef { guid: second_needed_chunk.guid, offset: 0, size: 4 }],
|
||||
},
|
||||
],
|
||||
compress: false,
|
||||
meta_tail: Vec::new(),
|
||||
});
|
||||
let target_bytes = build(&TestManifest {
|
||||
version: 21,
|
||||
build: "target".into(),
|
||||
exe: "Game.exe".into(),
|
||||
prereq: None,
|
||||
chunks: vec![needed_chunk.clone(), second_needed_chunk.clone()],
|
||||
files: vec![
|
||||
TestFile {
|
||||
path: "source.bin".into(),
|
||||
sha1: Sha1::digest(b"abcd").into(),
|
||||
tags: Vec::new(),
|
||||
parts: vec![PartRef { guid: needed_chunk.guid, offset: 0, size: 4 }],
|
||||
},
|
||||
TestFile {
|
||||
path: "second-source.bin".into(),
|
||||
sha1: Sha1::digest(b"efgh").into(),
|
||||
tags: Vec::new(),
|
||||
parts: vec![PartRef { guid: second_needed_chunk.guid, offset: 0, size: 4 }],
|
||||
},
|
||||
],
|
||||
compress: false,
|
||||
meta_tail: Vec::new(),
|
||||
});
|
||||
let installed = crate::epic::manifest::parse(&installed_bytes).unwrap();
|
||||
let target = crate::epic::manifest::parse(&target_bytes).unwrap();
|
||||
fs::write(game.join("source.bin"), b"abcd").unwrap();
|
||||
fs::write(game.join("irrelevant.bin"), b"wxyz").unwrap();
|
||||
fs::write(game.join("second-source.bin"), b"efgh").unwrap();
|
||||
let checked = std::cell::RefCell::new(Vec::new());
|
||||
let cancel = AtomicBool::new(false);
|
||||
let (seeded, written) = seed_from_verified_installed_with_check(
|
||||
&cache,
|
||||
&game,
|
||||
&installed,
|
||||
&target,
|
||||
&HashSet::from([0, 1]),
|
||||
&[],
|
||||
8,
|
||||
&cancel,
|
||||
|path, size, sha1, cancel| {
|
||||
checked.borrow_mut().push(path.file_name().unwrap().to_owned());
|
||||
super::super::delta::check(path, size, sha1, cancel)
|
||||
},
|
||||
);
|
||||
assert_eq!(seeded.len(), 2);
|
||||
assert!(seeded.contains(&0));
|
||||
assert!(seeded.contains(&1));
|
||||
assert_eq!(written, 8);
|
||||
assert_eq!(
|
||||
*checked.borrow(),
|
||||
vec![
|
||||
std::ffi::OsString::from("source.bin"),
|
||||
std::ffi::OsString::from("second-source.bin"),
|
||||
]
|
||||
);
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,9 @@ pub enum Check {
|
||||
}
|
||||
|
||||
fn hash_file(path: &Path, cancel: &AtomicBool) -> Option<Option<Hash>> {
|
||||
let Ok(mut f) = fs::File::open(path) else { return Some(None) };
|
||||
let Ok(mut f) = fs::File::open(path) else {
|
||||
return Some(None);
|
||||
};
|
||||
let mut h = Sha1::new();
|
||||
let mut buf = vec![0u8; 1024 * 1024];
|
||||
loop {
|
||||
@@ -31,10 +33,13 @@ fn hash_file(path: &Path, cancel: &AtomicBool) -> Option<Option<Hash>> {
|
||||
}
|
||||
|
||||
pub fn check(dest: &Path, size: u64, sha1: Option<Hash>, cancel: &AtomicBool) -> Check {
|
||||
let old_size = match fs::metadata(dest) {
|
||||
Ok(m) if m.is_file() => m.len(),
|
||||
let old_size = match fs::symlink_metadata(dest) {
|
||||
Ok(m) if m.is_file() && !m.file_type().is_symlink() => m.len(),
|
||||
_ => return Check::Pending { old_size: 0 },
|
||||
};
|
||||
if old_size == 0 && size == 0 && sha1.is_none() {
|
||||
return Check::UpToDate;
|
||||
}
|
||||
let Some(expected) = sha1 else {
|
||||
return Check::Pending { old_size };
|
||||
};
|
||||
@@ -61,10 +66,25 @@ mod tests {
|
||||
let good: Hash = Sha1::digest(b"hello").into();
|
||||
let cancel = AtomicBool::new(false);
|
||||
assert!(matches!(check(&f, 5, Some(good), &cancel), Check::UpToDate));
|
||||
assert!(matches!(check(&f, 5, None, &cancel), Check::Pending { old_size: 5 }));
|
||||
assert!(matches!(check(&f, 6, Some(good), &cancel), Check::Pending { old_size: 5 }));
|
||||
assert!(matches!(check(&f, 5, Some([0; 20]), &cancel), Check::Pending { .. }));
|
||||
assert!(matches!(check(&dir.join("missing"), 5, Some(good), &cancel), Check::Pending { old_size: 0 }));
|
||||
let empty = dir.join("empty.bin");
|
||||
fs::write(&empty, b"").unwrap();
|
||||
assert!(matches!(check(&empty, 0, None, &cancel), Check::UpToDate));
|
||||
assert!(matches!(
|
||||
check(&f, 5, None, &cancel),
|
||||
Check::Pending { old_size: 5 }
|
||||
));
|
||||
assert!(matches!(
|
||||
check(&f, 6, Some(good), &cancel),
|
||||
Check::Pending { old_size: 5 }
|
||||
));
|
||||
assert!(matches!(
|
||||
check(&f, 5, Some([0; 20]), &cancel),
|
||||
Check::Pending { .. }
|
||||
));
|
||||
assert!(matches!(
|
||||
check(&dir.join("missing"), 5, Some(good), &cancel),
|
||||
Check::Pending { old_size: 0 }
|
||||
));
|
||||
cancel.store(true, Ordering::Relaxed);
|
||||
assert!(matches!(check(&f, 5, Some(good), &cancel), Check::Cancelled));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
|
||||
@@ -14,7 +14,7 @@ use serde_json::{json, Value};
|
||||
|
||||
use super::build_info::{self, BuildInfo};
|
||||
use super::locale;
|
||||
use super::manifest::{self, Manifest};
|
||||
use super::manifest::{self, FileEntry, Manifest};
|
||||
use super::net;
|
||||
use schedule::{PlanFile, PlanPart};
|
||||
|
||||
@@ -40,9 +40,11 @@ pub enum Stop {
|
||||
pub struct Request {
|
||||
pub info: BuildInfo,
|
||||
pub game_dir: PathBuf,
|
||||
pub target_manifest_path: Option<PathBuf>,
|
||||
pub scratch_dir: Option<PathBuf>,
|
||||
pub storage_label: String,
|
||||
pub tags: Vec<String>,
|
||||
pub previous_tags: Vec<String>,
|
||||
pub max_workers: usize,
|
||||
pub process_workers: usize,
|
||||
pub ca_bundle: String,
|
||||
@@ -56,17 +58,32 @@ impl Request {
|
||||
return Err("No install folder was given".into());
|
||||
}
|
||||
let scratch = net::str_of(v, "scratchDir");
|
||||
let tags = v
|
||||
let tags: Vec<String> = v
|
||||
.get("tags")
|
||||
.and_then(|t| t.as_array())
|
||||
.map(|a| a.iter().filter_map(|t| t.as_str()).map(str::to_string).collect())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|t| t.as_str())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let previous_tags = v
|
||||
.get("previousTags")
|
||||
.and_then(|t| t.as_array())
|
||||
.map(|a| a.iter().filter_map(|t| t.as_str()).map(str::to_string).collect())
|
||||
.unwrap_or_else(|| tags.clone());
|
||||
Ok(Request {
|
||||
info,
|
||||
game_dir: PathBuf::from(game_dir),
|
||||
target_manifest_path: match net::str_of(v, "targetManifestPath") {
|
||||
"" => None,
|
||||
path => Some(PathBuf::from(path)),
|
||||
},
|
||||
scratch_dir: (!scratch.is_empty()).then(|| PathBuf::from(scratch)),
|
||||
storage_label: Some(net::str_of(v, "storageLabel")).filter(|s| !s.is_empty()).unwrap_or("storage").to_string(),
|
||||
tags,
|
||||
previous_tags,
|
||||
max_workers: v.get("maxWorkers").and_then(|n| n.as_u64()).unwrap_or(32) as usize,
|
||||
process_workers: v.get("processWorkers").and_then(|n| n.as_u64()).unwrap_or(2) as usize,
|
||||
ca_bundle: net::str_of(v, "caBundle").to_string(),
|
||||
@@ -106,7 +123,11 @@ impl Finished {
|
||||
pub fn safe_relative(path: &str) -> bool {
|
||||
!path.is_empty()
|
||||
&& !path.starts_with('/')
|
||||
&& path.split('/').all(|seg| !seg.is_empty() && seg != "." && seg != "..")
|
||||
&& path != ".droiddeck-maintenance"
|
||||
&& !path.starts_with(".droiddeck-maintenance/")
|
||||
&& path
|
||||
.split('/')
|
||||
.all(|seg| !seg.is_empty() && seg != "." && seg != "..")
|
||||
}
|
||||
|
||||
fn dir_has_entries(dir: &Path) -> bool {
|
||||
@@ -140,14 +161,182 @@ pub fn fetch_manifest(info: &BuildInfo, log: &dyn Fn(&str)) -> Result<Manifest,
|
||||
})
|
||||
}
|
||||
|
||||
fn installed_manifest_path(game_dir: &Path) -> PathBuf {
|
||||
game_dir.join(".droiddeck-maintenance/epic/installed.manifest")
|
||||
}
|
||||
|
||||
fn read_installed_manifest(game_dir: &Path, log: &dyn Fn(&str)) -> Option<Manifest> {
|
||||
let path = installed_manifest_path(game_dir);
|
||||
match fs::symlink_metadata(&path) {
|
||||
Ok(meta) if meta.is_file() && !meta.file_type().is_symlink() => {}
|
||||
Ok(_) => {
|
||||
log("obsolete Epic files preserved: retained manifest is not a regular file");
|
||||
return None;
|
||||
}
|
||||
Err(_) => return None,
|
||||
}
|
||||
match fs::read(path).ok().and_then(|bytes| manifest::parse(&bytes).ok()) {
|
||||
Some(manifest) => Some(manifest),
|
||||
None => {
|
||||
log("obsolete Epic files preserved: retained manifest is unavailable or invalid");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_target_manifest(req: &Request) -> Result<Option<Vec<u8>>, String> {
|
||||
let Some(path) = &req.target_manifest_path else {
|
||||
return Ok(None);
|
||||
};
|
||||
let root = req
|
||||
.game_dir
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("Could not resolve the install folder: {e}"))?;
|
||||
if fs::symlink_metadata(path)
|
||||
.map(|m| m.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err("The pinned Epic manifest is a symbolic link".into());
|
||||
}
|
||||
let candidate = path
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("The pinned Epic manifest is unavailable: {e}"))?;
|
||||
if !candidate.starts_with(&root) || !candidate.is_file() {
|
||||
return Err("The pinned Epic manifest is outside the install folder".into());
|
||||
}
|
||||
fs::read(candidate)
|
||||
.map(Some)
|
||||
.map_err(|e| format!("Could not read the pinned Epic manifest: {e}"))
|
||||
}
|
||||
|
||||
fn write_installed_manifest(game_dir: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||
let metadata = game_dir.join(".droiddeck-maintenance");
|
||||
if fs::symlink_metadata(&metadata)
|
||||
.map(|m| m.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err("Epic maintenance metadata is a symbolic link".into());
|
||||
}
|
||||
let dir = metadata.join("epic");
|
||||
if fs::symlink_metadata(&dir)
|
||||
.map(|m| m.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err("Epic maintenance metadata is a symbolic link".into());
|
||||
}
|
||||
fs::create_dir_all(&dir)
|
||||
.map_err(|e| format!("Could not save the Epic install manifest: {e}"))?;
|
||||
let temp = dir.join("installed.manifest.tmp");
|
||||
if fs::symlink_metadata(&temp)
|
||||
.map(|m| m.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err("Epic maintenance metadata is a symbolic link".into());
|
||||
}
|
||||
fs::write(&temp, bytes)
|
||||
.map_err(|e| format!("Could not save the Epic install manifest: {e}"))?;
|
||||
fs::rename(&temp, installed_manifest_path(game_dir))
|
||||
.map_err(|e| format!("Could not save the Epic install manifest: {e}"))
|
||||
}
|
||||
|
||||
fn cleanup_obsolete(
|
||||
game_dir: &Path,
|
||||
old: &[FileEntry],
|
||||
old_tags: &[String],
|
||||
new: &[FileEntry],
|
||||
new_tags: &[String],
|
||||
cancel: &AtomicBool,
|
||||
ev: &dyn Events,
|
||||
log: &dyn Fn(&str),
|
||||
) -> Result<bool, Stop> {
|
||||
let old_selected = locale::select(old, Some(old_tags));
|
||||
let new_selected = locale::select(new, Some(new_tags));
|
||||
let key = |path: &str| -> Option<String> {
|
||||
if !safe_relative(path) {
|
||||
return None;
|
||||
}
|
||||
Some(path.replace('\\', "/").to_lowercase())
|
||||
};
|
||||
let inventory = |files: &[FileEntry], indices: &[usize]| -> Option<HashSet<String>> {
|
||||
let mut out = HashSet::new();
|
||||
for &i in indices {
|
||||
if !out.insert(key(&files[i].path)?) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
};
|
||||
let Some(old_keys) = inventory(old, &old_selected) else {
|
||||
log("obsolete Epic files preserved: old inventory contains unsafe or case-colliding paths");
|
||||
return Ok(cancel.load(Ordering::Relaxed));
|
||||
};
|
||||
let Some(new_keys) = inventory(new, &new_selected) else {
|
||||
log("obsolete Epic files preserved: target inventory contains unsafe or case-colliding paths");
|
||||
return Ok(cancel.load(Ordering::Relaxed));
|
||||
};
|
||||
let _ = old_keys;
|
||||
let Ok(root) = game_dir.canonicalize() else {
|
||||
log("obsolete Epic files preserved: install folder could not be resolved");
|
||||
return Ok(cancel.load(Ordering::Relaxed));
|
||||
};
|
||||
let mut removed = 0usize;
|
||||
let mut preserved = 0usize;
|
||||
for i in old_selected {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
log("obsolete Epic cleanup cancelled; remaining files were preserved");
|
||||
return Ok(true);
|
||||
}
|
||||
let file = &old[i];
|
||||
let Some(k) = key(&file.path) else { preserved += 1; continue };
|
||||
if new_keys.contains(&k) { continue; }
|
||||
let Some(expected) = file.sha1 else { preserved += 1; continue };
|
||||
let mut path = game_dir.to_path_buf();
|
||||
let mut safe = true;
|
||||
for segment in file.path.split('/') {
|
||||
path.push(segment);
|
||||
if fs::symlink_metadata(&path).map(|m| m.file_type().is_symlink()).unwrap_or(false) {
|
||||
safe = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Ok(metadata) = fs::symlink_metadata(&path) else { continue };
|
||||
let Ok(canonical) = path.canonicalize() else { preserved += 1; continue };
|
||||
if !safe || !metadata.is_file() || !canonical.starts_with(&root) {
|
||||
preserved += 1;
|
||||
continue;
|
||||
}
|
||||
if !matches!(delta::check(&canonical, file.size, Some(expected), cancel), delta::Check::UpToDate) {
|
||||
preserved += 1;
|
||||
continue;
|
||||
}
|
||||
if !ev.before_replace() {
|
||||
return Err(Stop::Failed("The install record could not be switched to updating; nothing was replaced".into()));
|
||||
}
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
log("obsolete Epic cleanup cancelled; remaining files were preserved");
|
||||
return Ok(true);
|
||||
}
|
||||
if fs::remove_file(&canonical).is_ok() { removed += 1; } else { preserved += 1; }
|
||||
}
|
||||
log(&format!("obsolete Epic cleanup removed={removed} preserved={preserved}"));
|
||||
Ok(cancel.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
fn resume_from(stage: &Path, parts: &[PlanPart], size: u64) -> Option<HashSet<u64>> {
|
||||
let meta = fs::symlink_metadata(stage).ok()?;
|
||||
if !meta.is_file() || meta.len() > size {
|
||||
return None;
|
||||
}
|
||||
let list = fs::read_to_string(staging::list_path(stage)).ok()?;
|
||||
let kept: HashSet<u64> = list.lines().map(|l| l.parse().ok()).collect::<Option<_>>()?;
|
||||
let fits = |o: &u64| parts.iter().any(|p| p.file_offset == *o && p.file_offset + p.size as u64 <= meta.len());
|
||||
let kept: HashSet<u64> = list
|
||||
.lines()
|
||||
.map(|l| l.parse().ok())
|
||||
.collect::<Option<_>>()?;
|
||||
let fits = |o: &u64| {
|
||||
parts
|
||||
.iter()
|
||||
.any(|p| p.file_offset == *o && p.file_offset + p.size as u64 <= meta.len())
|
||||
};
|
||||
(!kept.is_empty() && kept.iter().all(fits)).then_some(kept)
|
||||
}
|
||||
|
||||
@@ -155,7 +344,17 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
let failed = |m: String| Stop::Failed(m);
|
||||
ev.status("Downloading the manifest…");
|
||||
let log = |line: &str| ev.log(line);
|
||||
let manifest = fetch_manifest(&req.info, &log).map_err(failed)?;
|
||||
let pinned_manifest = read_target_manifest(req).map_err(failed)?;
|
||||
let manifest_bytes = match pinned_manifest {
|
||||
Some(bytes) => bytes,
|
||||
None => build_info::download_manifest(&req.info, &req.info.cdns, &log)
|
||||
.ok_or_else(|| failed("The manifest could not be downloaded".into()))?,
|
||||
};
|
||||
let manifest = manifest::parse(&manifest_bytes).map_err(|e| {
|
||||
ev.log(&format!("manifest parse: {e}"));
|
||||
failed("The manifest could not be parsed".into())
|
||||
})?;
|
||||
let installed_manifest = read_installed_manifest(&req.game_dir, &log);
|
||||
cancelled(cancel)?;
|
||||
ev.status("Reading the manifest…");
|
||||
|
||||
@@ -166,7 +365,9 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
return Err(failed(format!("The manifest has an unsafe path: {path}")));
|
||||
}
|
||||
if staging::conflicts(path) {
|
||||
return Err(failed("The manifest conflicts with the staging folder".into()));
|
||||
return Err(failed(
|
||||
"The manifest conflicts with the staging folder".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let disk_bytes: u64 = selected.iter().map(|&i| manifest.files[i].size).sum();
|
||||
@@ -229,6 +430,25 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
ev.log("every selected file is already up to date");
|
||||
clean_caches();
|
||||
ev.installing(disk_bytes, disk_bytes, total_selected, total_selected);
|
||||
let cleanup_cancelled = if let Some(installed) = installed_manifest.as_ref() {
|
||||
cleanup_obsolete(
|
||||
&req.game_dir,
|
||||
&installed.files,
|
||||
&req.previous_tags,
|
||||
&manifest.files,
|
||||
&req.tags,
|
||||
cancel,
|
||||
ev,
|
||||
&log,
|
||||
)?
|
||||
} else {
|
||||
ev.log("obsolete Epic files preserved: no retained prior manifest is available");
|
||||
cancel.load(Ordering::Relaxed)
|
||||
};
|
||||
if cleanup_cancelled || cancel.load(Ordering::Relaxed) {
|
||||
return Err(Stop::Cancelled);
|
||||
}
|
||||
write_installed_manifest(&req.game_dir, &manifest_bytes).map_err(failed)?;
|
||||
return Ok(finished);
|
||||
}
|
||||
|
||||
@@ -248,7 +468,12 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
if info.window_exact && part.offset as u64 + part.size as u64 > info.window as u64 {
|
||||
return Err(failed(format!("A chunk is too short for {}", f.path)));
|
||||
}
|
||||
parts.push(PlanPart { chunk: c as u32, chunk_offset: part.offset, size: part.size, file_offset: offset });
|
||||
parts.push(PlanPart {
|
||||
chunk: c as u32,
|
||||
chunk_offset: part.offset,
|
||||
size: part.size,
|
||||
file_offset: offset,
|
||||
});
|
||||
offset += part.size as u64;
|
||||
}
|
||||
let mut resume = None;
|
||||
@@ -261,13 +486,19 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
resumed_bytes += bytes;
|
||||
kept_size = bytes;
|
||||
parts.retain(|p| !kept.contains(&p.file_offset));
|
||||
resume = Some(writer::Resume { stage, kept: kept.into_iter().collect() });
|
||||
resume = Some(writer::Resume {
|
||||
stage,
|
||||
kept: kept.into_iter().collect(),
|
||||
});
|
||||
}
|
||||
None => staging::remove_partial(&stage),
|
||||
}
|
||||
}
|
||||
kept_sizes.push(kept_size);
|
||||
plan_files.push(PlanFile { size: f.size, parts: parts.clone() });
|
||||
plan_files.push(PlanFile {
|
||||
size: f.size,
|
||||
parts: parts.clone(),
|
||||
});
|
||||
engine_files.push(writer::EngineFile {
|
||||
path: f.path.clone(),
|
||||
dest: req.game_dir.join(&f.path),
|
||||
@@ -292,10 +523,15 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
let sizes: Vec<space::PendingSize> = pending
|
||||
.iter()
|
||||
.zip(&kept_sizes)
|
||||
.map(|(&(i, old), kept)| space::PendingSize { new_size: manifest.files[i].size - kept, old_size: old })
|
||||
.map(|(&(i, old), kept)| space::PendingSize {
|
||||
new_size: manifest.files[i].size - kept,
|
||||
old_size: old,
|
||||
})
|
||||
.collect();
|
||||
let free_game = space::free_bytes(&req.game_dir);
|
||||
let scratch_space = scratch.as_ref().map(|s| space::Scratch { free: space::free_bytes(s) });
|
||||
let scratch_space = scratch.as_ref().map(|s| space::Scratch {
|
||||
free: space::free_bytes(s),
|
||||
});
|
||||
let plan = space::plan(&sizes, free_game, scratch_space, &req.storage_label).map_err(failed)?;
|
||||
let cache_dir = match (&scratch, plan.cache_on_scratch) {
|
||||
(Some(s), true) => s.clone(),
|
||||
@@ -311,7 +547,51 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
position += 1;
|
||||
}
|
||||
}
|
||||
let reused = cache::prepare(&cache_dir, &manifest.chunks, &first_use, plan.cache_budget, cancel);
|
||||
let mut reused = cache::prepare(
|
||||
&cache_dir,
|
||||
&manifest.chunks,
|
||||
&first_use,
|
||||
plan.cache_budget,
|
||||
cancel,
|
||||
);
|
||||
if let Some(installed) = installed_manifest.as_ref() {
|
||||
let needed_chunks: HashSet<u32> = first_use.keys().copied().collect();
|
||||
let cached_bytes: u64 = reused
|
||||
.iter()
|
||||
.map(|i| manifest.chunks[*i as usize].window as u64)
|
||||
.sum();
|
||||
let remaining_budget = plan.cache_budget.saturating_sub(cached_bytes);
|
||||
let (seeded, _) = cache::seed_from_verified_installed(
|
||||
&cache_dir,
|
||||
&req.game_dir,
|
||||
installed,
|
||||
&manifest,
|
||||
&needed_chunks,
|
||||
&reused,
|
||||
remaining_budget,
|
||||
cancel,
|
||||
);
|
||||
if !seeded.is_empty() {
|
||||
reused = cache::prepare(
|
||||
&cache_dir,
|
||||
&manifest.chunks,
|
||||
&first_use,
|
||||
plan.cache_budget,
|
||||
cancel,
|
||||
);
|
||||
let retained: Vec<u32> = seeded.into_iter().filter(|i| reused.contains(i)).collect();
|
||||
let bytes: u64 = retained
|
||||
.iter()
|
||||
.map(|i| manifest.chunks[*i as usize].window as u64)
|
||||
.sum();
|
||||
if !retained.is_empty() {
|
||||
ev.log(&format!(
|
||||
"reused {} verified installed-file chunks ({bytes} bytes)",
|
||||
retained.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
cancelled(cancel)?;
|
||||
let windows: Vec<u32> = manifest.chunks.iter().map(|c| c.window).collect();
|
||||
let schedule = schedule::build(&plan_files, &windows, plan.cache_budget, &reused);
|
||||
@@ -356,6 +636,25 @@ cache_budget_mib={} overlap_mib={} free_game={free_game} workers={} process_work
|
||||
finished.files_written = stats.files_written;
|
||||
clean_caches();
|
||||
ev.installing(disk_bytes, disk_bytes, total_selected, total_selected);
|
||||
let cleanup_cancelled = if let Some(installed) = installed_manifest.as_ref() {
|
||||
cleanup_obsolete(
|
||||
&req.game_dir,
|
||||
&installed.files,
|
||||
&req.previous_tags,
|
||||
&manifest.files,
|
||||
&req.tags,
|
||||
cancel,
|
||||
ev,
|
||||
&log,
|
||||
)?
|
||||
} else {
|
||||
ev.log("obsolete Epic files preserved: no retained prior manifest is available");
|
||||
cancel.load(Ordering::Relaxed)
|
||||
};
|
||||
if cleanup_cancelled || cancel.load(Ordering::Relaxed) {
|
||||
return Err(Stop::Cancelled);
|
||||
}
|
||||
write_installed_manifest(&req.game_dir, &manifest_bytes).map_err(failed)?;
|
||||
Ok(finished)
|
||||
}
|
||||
|
||||
|
||||
@@ -95,7 +95,13 @@ pub fn build(files: &[PlanFile], windows: &[u32], budget: u64, cached: &[u32]) -
|
||||
}
|
||||
occupancy += window(c);
|
||||
let id = producers.len() as u32;
|
||||
producers.push(Producer { chunk: c, anchor: NONE, preloaded: true, copy: 0, uses: Vec::new() });
|
||||
producers.push(Producer {
|
||||
chunk: c,
|
||||
anchor: NONE,
|
||||
preloaded: true,
|
||||
copy: 0,
|
||||
uses: Vec::new(),
|
||||
});
|
||||
copies.insert(c, 1);
|
||||
active.insert(c, id);
|
||||
resident.insert(c, u);
|
||||
@@ -114,7 +120,13 @@ pub fn build(files: &[PlanFile], windows: &[u32], budget: u64, cached: &[u32]) -
|
||||
None => {
|
||||
let id = producers.len() as u32;
|
||||
let copy = copies.entry(c).or_insert(0);
|
||||
producers.push(Producer { chunk: c, anchor: f, preloaded: false, copy: *copy, uses: Vec::new() });
|
||||
producers.push(Producer {
|
||||
chunk: c,
|
||||
anchor: f,
|
||||
preloaded: false,
|
||||
copy: *copy,
|
||||
uses: Vec::new(),
|
||||
});
|
||||
*copy += 1;
|
||||
fetch.push(id);
|
||||
active.insert(c, id);
|
||||
@@ -161,8 +173,19 @@ pub fn build(files: &[PlanFile], windows: &[u32], budget: u64, cached: &[u32]) -
|
||||
}
|
||||
}
|
||||
|
||||
let refetches = producers.iter().filter(|p| !p.preloaded && p.copy > 0).count() as u32;
|
||||
Schedule { file_start, use_file, use_producer, producers, fetch, peak_cache: peak, refetches }
|
||||
let refetches = producers
|
||||
.iter()
|
||||
.filter(|p| !p.preloaded && p.copy > 0)
|
||||
.count() as u32;
|
||||
Schedule {
|
||||
file_start,
|
||||
use_file,
|
||||
use_producer,
|
||||
producers,
|
||||
fetch,
|
||||
peak_cache: peak,
|
||||
refetches,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -176,7 +199,12 @@ mod tests {
|
||||
parts: chunks
|
||||
.iter()
|
||||
.map(|&c| {
|
||||
let p = PlanPart { chunk: c, chunk_offset: 0, size: 10, file_offset: off };
|
||||
let p = PlanPart {
|
||||
chunk: c,
|
||||
chunk_offset: 0,
|
||||
size: 10,
|
||||
file_offset: off,
|
||||
};
|
||||
off += 10;
|
||||
p
|
||||
})
|
||||
@@ -228,7 +256,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn cached_chunks_are_reused_soonest_first() {
|
||||
let s = build(&[file(&[0]), file(&[1]), file(&[2])], &[10, 10, 10], 20, &[2, 0, 1, 7]);
|
||||
let s = build(
|
||||
&[file(&[0]), file(&[1]), file(&[2])],
|
||||
&[10, 10, 10],
|
||||
20,
|
||||
&[2, 0, 1, 7],
|
||||
);
|
||||
assert!(s.fetch.is_empty() || s.fetch.iter().all(|&p| s.producers[p as usize].chunk == 2));
|
||||
let preloaded: Vec<u32> = s.producers.iter().filter(|p| p.preloaded).map(|p| p.chunk).collect();
|
||||
assert_eq!(preloaded, vec![0, 1]);
|
||||
|
||||
@@ -115,7 +115,12 @@ pub fn net_peak(pending: &[PendingSize]) -> u64 {
|
||||
peak.max(0) as u64
|
||||
}
|
||||
|
||||
pub fn plan(pending: &[PendingSize], free_game: i64, scratch: Option<Scratch>, label: &str) -> Result<SpacePlan, String> {
|
||||
pub fn plan(
|
||||
pending: &[PendingSize],
|
||||
free_game: i64,
|
||||
scratch: Option<Scratch>,
|
||||
label: &str,
|
||||
) -> Result<SpacePlan, String> {
|
||||
let peak = net_peak(pending);
|
||||
let largest_replaced = pending.iter().filter(|p| p.old_size > 0).map(|p| p.new_size).max();
|
||||
|
||||
@@ -139,7 +144,11 @@ pub fn plan(pending: &[PendingSize], free_game: i64, scratch: Option<Scratch>, l
|
||||
if free_game < 0 {
|
||||
largest
|
||||
} else {
|
||||
largest.max((free_game as u64).saturating_sub(peak).saturating_sub(cache_on_game))
|
||||
largest.max(
|
||||
(free_game as u64)
|
||||
.saturating_sub(peak)
|
||||
.saturating_sub(cache_on_game),
|
||||
)
|
||||
}
|
||||
});
|
||||
let game_need = peak + overlap.unwrap_or(0) + cache_on_game;
|
||||
@@ -184,7 +193,9 @@ pub fn plan(pending: &[PendingSize], free_game: i64, scratch: Option<Scratch>, l
|
||||
human(peak.saturating_sub(free))
|
||||
);
|
||||
if moved {
|
||||
message.push_str(". The download cache had to move beside the game because internal storage is full");
|
||||
message.push_str(
|
||||
". The download cache had to move beside the game because internal storage is full",
|
||||
);
|
||||
}
|
||||
Err(message)
|
||||
}
|
||||
@@ -196,15 +207,27 @@ mod tests {
|
||||
const GB: u64 = 1024 * MIB;
|
||||
|
||||
fn fresh(sizes: &[u64]) -> Vec<PendingSize> {
|
||||
sizes.iter().map(|&s| PendingSize { new_size: s, old_size: 0 }).collect()
|
||||
sizes
|
||||
.iter()
|
||||
.map(|&s| PendingSize {
|
||||
new_size: s,
|
||||
old_size: 0,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn net_peak_credits_old_copies_at_their_swap() {
|
||||
assert_eq!(net_peak(&fresh(&[10, 20])), 30);
|
||||
let update = vec![
|
||||
PendingSize { new_size: 100, old_size: 90 },
|
||||
PendingSize { new_size: 50, old_size: 60 },
|
||||
PendingSize {
|
||||
new_size: 100,
|
||||
old_size: 90,
|
||||
},
|
||||
PendingSize {
|
||||
new_size: 50,
|
||||
old_size: 60,
|
||||
},
|
||||
];
|
||||
assert_eq!(net_peak(&update), 100);
|
||||
assert_eq!(net_peak(&[PendingSize { new_size: 5, old_size: 500 }]), 5);
|
||||
@@ -224,13 +247,24 @@ mod tests {
|
||||
let p = plan(&fresh(&[50 * GB]), -1, Some(Scratch { free: -1 }), "Card").unwrap();
|
||||
assert!(p.cache_on_scratch);
|
||||
assert_eq!(p.cache_budget, CACHE_WHEN_UNKNOWN);
|
||||
let update = vec![PendingSize { new_size: GB, old_size: GB }];
|
||||
let update = vec![PendingSize {
|
||||
new_size: GB,
|
||||
old_size: GB,
|
||||
}];
|
||||
assert_eq!(plan(&update, -1, None, "Card").unwrap().overlap, Some(GB));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scratch_too_small_moves_the_cache_beside_the_game() {
|
||||
let p = plan(&fresh(&[GB]), (20 * GB) as i64, Some(Scratch { free: (100 * MIB) as i64 }), "Card").unwrap();
|
||||
let p = plan(
|
||||
&fresh(&[GB]),
|
||||
(20 * GB) as i64,
|
||||
Some(Scratch {
|
||||
free: (100 * MIB) as i64,
|
||||
}),
|
||||
"Card",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!p.cache_on_scratch && p.cache_moved_beside_game);
|
||||
}
|
||||
|
||||
@@ -256,8 +290,14 @@ mod tests {
|
||||
#[test]
|
||||
fn updates_get_an_overlap_budget_of_at_least_the_largest_replaced_file() {
|
||||
let update = vec![
|
||||
PendingSize { new_size: GB, old_size: GB },
|
||||
PendingSize { new_size: 2 * GB, old_size: 2 * GB },
|
||||
PendingSize {
|
||||
new_size: GB,
|
||||
old_size: GB,
|
||||
},
|
||||
PendingSize {
|
||||
new_size: 2 * GB,
|
||||
old_size: 2 * GB,
|
||||
},
|
||||
];
|
||||
let p = plan(&update, (40 * GB) as i64, None, "Internal").unwrap();
|
||||
assert!(p.overlap.unwrap() >= 2 * GB);
|
||||
|
||||
@@ -44,7 +44,9 @@ pub fn remove_partial(partial: &Path) {
|
||||
}
|
||||
|
||||
pub fn partials(dir: &Path) -> HashMap<String, PathBuf> {
|
||||
let Ok(entries) = fs::read_dir(dir) else { return HashMap::new() };
|
||||
let Ok(entries) = fs::read_dir(dir) else {
|
||||
return HashMap::new();
|
||||
};
|
||||
entries
|
||||
.flatten()
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
@@ -77,7 +79,11 @@ pub fn recover(game_dir: &Path) -> Result<PathBuf, String> {
|
||||
let game = fs::canonicalize(game_dir).map_err(|e| format!("game folder: {e}"))?;
|
||||
let expected = game.join(DIR_NAME);
|
||||
let dir = game_dir.join(DIR_NAME);
|
||||
let refuse = |why: &str| Err(format!("The staging folder {DIR_NAME} is not usable ({why}); nothing was changed"));
|
||||
let refuse = |why: &str| {
|
||||
Err(format!(
|
||||
"The staging folder {DIR_NAME} is not usable ({why}); nothing was changed"
|
||||
))
|
||||
};
|
||||
|
||||
match fs::symlink_metadata(&dir) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
@@ -140,8 +146,13 @@ pub fn recover(game_dir: &Path) -> Result<PathBuf, String> {
|
||||
}
|
||||
|
||||
pub fn remove_if_idle(dir: &Path) {
|
||||
let Ok(entries) = fs::read_dir(dir) else { return };
|
||||
let names: Vec<String> = entries.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
|
||||
let Ok(entries) = fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
let names: Vec<String> = entries
|
||||
.flatten()
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
if names.iter().all(|n| n == OWNER_FILE) {
|
||||
let marker = dir.join(OWNER_FILE);
|
||||
if names.is_empty() || fs::read(&marker).map(|c| c == OWNER_MARKER).unwrap_or(false) {
|
||||
|
||||
@@ -117,8 +117,16 @@ fn fixture() -> Fixture {
|
||||
sha1: sha(&a),
|
||||
tags: vec![],
|
||||
parts: vec![
|
||||
PartRef { guid: c1.guid, offset: 0, size: 3000 },
|
||||
PartRef { guid: c2.guid, offset: 100, size: 1000 },
|
||||
PartRef {
|
||||
guid: c1.guid,
|
||||
offset: 0,
|
||||
size: 3000,
|
||||
},
|
||||
PartRef {
|
||||
guid: c2.guid,
|
||||
offset: 100,
|
||||
size: 1000,
|
||||
},
|
||||
],
|
||||
},
|
||||
TestFile {
|
||||
@@ -126,22 +134,43 @@ fn fixture() -> Fixture {
|
||||
sha1: sha(&c),
|
||||
tags: vec!["English".into()],
|
||||
parts: vec![
|
||||
PartRef { guid: c1.guid, offset: 3000, size: 1096 },
|
||||
PartRef { guid: c3.guid, offset: 0, size: 1000 },
|
||||
PartRef {
|
||||
guid: c1.guid,
|
||||
offset: 3000,
|
||||
size: 1096,
|
||||
},
|
||||
PartRef {
|
||||
guid: c3.guid,
|
||||
offset: 0,
|
||||
size: 1000,
|
||||
},
|
||||
],
|
||||
},
|
||||
TestFile {
|
||||
path: "d.bin".into(),
|
||||
sha1: sha(&d),
|
||||
tags: vec![],
|
||||
parts: vec![PartRef { guid: c2.guid, offset: 0, size: 100 }],
|
||||
parts: vec![PartRef {
|
||||
guid: c2.guid,
|
||||
offset: 0,
|
||||
size: 100,
|
||||
}],
|
||||
},
|
||||
TestFile {
|
||||
path: "e.txt".into(),
|
||||
sha1: [0; 20],
|
||||
tags: vec![],
|
||||
parts: vec![],
|
||||
},
|
||||
TestFile { path: "e.txt".into(), sha1: [0; 20], tags: vec![], parts: vec![] },
|
||||
TestFile {
|
||||
path: "fr.txt".into(),
|
||||
sha1: [0; 20],
|
||||
tags: vec!["French".into()],
|
||||
parts: vec![PartRef { guid: c3.guid, offset: 0, size: 10 }],
|
||||
parts: vec![PartRef {
|
||||
guid: c3.guid,
|
||||
offset: 0,
|
||||
size: 10,
|
||||
}],
|
||||
},
|
||||
];
|
||||
let m = TestManifest {
|
||||
@@ -159,7 +188,10 @@ fn fixture() -> Fixture {
|
||||
let mut served = HashMap::new();
|
||||
served.insert("/Builds/x/test.manifest".to_string(), manifest_bytes);
|
||||
for (info, data) in [(&c1, &d1), (&c2, &d2), (&c3, &d3)] {
|
||||
served.insert(format!("/Builds/x/{}", parsed.chunk_path(info)), encode(data, true));
|
||||
served.insert(
|
||||
format!("/Builds/x/{}", parsed.chunk_path(info)),
|
||||
encode(data, true),
|
||||
);
|
||||
}
|
||||
let hits = Arc::new(AtomicUsize::new(0));
|
||||
let base = serve(served, Arc::clone(&hits));
|
||||
@@ -178,15 +210,21 @@ fn fixture() -> Fixture {
|
||||
fn request(fx: &Fixture, game: &Path) -> Request {
|
||||
Request {
|
||||
info: BuildInfo {
|
||||
cdns: vec![Cdn { base: fx.base.clone(), dir: "/Builds/x".into(), auth: String::new() }],
|
||||
cdns: vec![Cdn {
|
||||
base: fx.base.clone(),
|
||||
dir: "/Builds/x".into(),
|
||||
auth: String::new(),
|
||||
}],
|
||||
manifest_file: "test.manifest".into(),
|
||||
build_version: "9.9".into(),
|
||||
deployment_id: "dep".into(),
|
||||
},
|
||||
game_dir: game.to_path_buf(),
|
||||
target_manifest_path: None,
|
||||
scratch_dir: None,
|
||||
storage_label: "Test storage".into(),
|
||||
tags: vec!["English".into(), "en-US".into(), "en".into()],
|
||||
previous_tags: vec!["English".into(), "en-US".into(), "en".into()],
|
||||
max_workers: 4,
|
||||
process_workers: 2,
|
||||
ca_bundle: String::new(),
|
||||
@@ -216,6 +254,11 @@ fn fresh_install_then_rerun_then_repair() {
|
||||
assert_eq!(done.prereq_path, "redist/setup.exe");
|
||||
assert!(done.prereq_read);
|
||||
assert_eq!(done.deployment_id, "dep");
|
||||
let installed_manifest = game.join(".droiddeck-maintenance/epic/installed.manifest");
|
||||
assert!(
|
||||
installed_manifest.is_file(),
|
||||
"the parsed installed manifest is retained without CDN credentials"
|
||||
);
|
||||
assert_eq!(done.disk_bytes, 4000 + 2096 + 100);
|
||||
assert_eq!(events.replaced.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(*events.last_progress.lock().unwrap(), (6196, 6196));
|
||||
@@ -223,17 +266,41 @@ fn fresh_install_then_rerun_then_repair() {
|
||||
assert!(!game.join(staging::DIR_NAME).exists());
|
||||
|
||||
let hits_before = fx.hits.load(Ordering::Relaxed);
|
||||
let mut pinned = request(&fx, &game);
|
||||
pinned.target_manifest_path = Some(installed_manifest);
|
||||
let pinned_events = Recorder::default();
|
||||
let pinned_result = run(&pinned, &cancel, &pinned_events).unwrap();
|
||||
assert_eq!(pinned_result.build_version, "9.9");
|
||||
assert_eq!(
|
||||
pinned_events.replaced.load(Ordering::SeqCst),
|
||||
0,
|
||||
"an already-correct repair writes no files"
|
||||
);
|
||||
assert_eq!(
|
||||
fx.hits.load(Ordering::Relaxed),
|
||||
hits_before,
|
||||
"pinned repair does not fetch the current manifest"
|
||||
);
|
||||
|
||||
let again = Recorder::default();
|
||||
run(&request(&fx, &game), &cancel, &again).unwrap();
|
||||
assert_eq!(fx.hits.load(Ordering::Relaxed) - hits_before, 1, "only the manifest is fetched");
|
||||
assert_eq!(again.sizes.lock().unwrap().0, 0);
|
||||
assert_eq!(again.replaced.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(
|
||||
again.replaced.load(Ordering::SeqCst),
|
||||
0,
|
||||
"the pinned files are already correct"
|
||||
);
|
||||
|
||||
fs::write(game.join("b/c.bin"), b"damaged").unwrap();
|
||||
let repair = Recorder::default();
|
||||
run(&request(&fx, &game), &cancel, &repair).unwrap();
|
||||
assert_eq!(fs::read(game.join("b/c.bin")).unwrap(), fx.expected[1].1);
|
||||
assert_eq!(repair.sizes.lock().unwrap().0, 2096 + 0, "the damaged file and the hashless empty file");
|
||||
assert_eq!(
|
||||
repair.sizes.lock().unwrap().0,
|
||||
2096,
|
||||
"only the damaged file needs repair"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
@@ -254,6 +321,80 @@ fn a_refused_update_switch_replaces_nothing() {
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obsolete_cleanup_removes_only_unchanged_prior_manifest_files() {
|
||||
let game = temp_game("obsolete-cleanup");
|
||||
fs::create_dir_all(&game).unwrap();
|
||||
fs::write(game.join("old.bin"), b"old").unwrap();
|
||||
fs::write(game.join("modified.bin"), b"user edit").unwrap();
|
||||
fs::write(game.join("untracked.bin"), b"untracked").unwrap();
|
||||
let old = vec![
|
||||
FileEntry { path: "old.bin".into(), sha1: Some(Sha1::digest(b"old").into()), tags: vec![], parts: vec![], size: 3 },
|
||||
FileEntry { path: "modified.bin".into(), sha1: Some(Sha1::digest(b"original").into()), tags: vec![], parts: vec![], size: 8 },
|
||||
];
|
||||
let new = vec![FileEntry { path: "current.bin".into(), sha1: None, tags: vec![], parts: vec![], size: 0 }];
|
||||
let cancel = AtomicBool::new(false);
|
||||
assert!(!cleanup_obsolete(&game, &old, &[], &new, &[], &cancel, &Recorder::default(), &|_| {}).unwrap());
|
||||
assert!(!game.join("old.bin").exists());
|
||||
assert_eq!(fs::read(game.join("modified.bin")).unwrap(), b"user edit");
|
||||
assert_eq!(fs::read(game.join("untracked.bin")).unwrap(), b"untracked");
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obsolete_cleanup_cancellation_preserves_the_old_inventory() {
|
||||
let game = temp_game("obsolete-cancel");
|
||||
fs::create_dir_all(&game).unwrap();
|
||||
fs::write(game.join("old.bin"), b"old").unwrap();
|
||||
let old = vec![FileEntry { path: "old.bin".into(), sha1: Some(Sha1::digest(b"old").into()), tags: vec![], parts: vec![], size: 3 }];
|
||||
let new = vec![FileEntry { path: "current.bin".into(), sha1: None, tags: vec![], parts: vec![], size: 0 }];
|
||||
let cancel = AtomicBool::new(true);
|
||||
assert!(cleanup_obsolete(&game, &old, &[], &new, &[], &cancel, &Recorder::default(), &|_| {}).unwrap());
|
||||
assert_eq!(fs::read(game.join("old.bin")).unwrap(), b"old");
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_obsolete_cleanup_preserves_file_and_installed_manifest() {
|
||||
let fx = fixture();
|
||||
let game = temp_game("obsolete-refused");
|
||||
fs::create_dir_all(&game).unwrap();
|
||||
let metadata = game.join(".droiddeck-maintenance/epic");
|
||||
fs::create_dir_all(&metadata).unwrap();
|
||||
let old_bytes = b"old";
|
||||
let old_chunk = chunk(90, old_bytes.len() as u32);
|
||||
let old_manifest = build(&TestManifest {
|
||||
version: 21,
|
||||
build: "old".into(),
|
||||
exe: "Old.exe".into(),
|
||||
prereq: None,
|
||||
chunks: vec![old_chunk.clone()],
|
||||
files: vec![TestFile {
|
||||
path: "obsolete.bin".into(),
|
||||
sha1: Sha1::digest(old_bytes).into(),
|
||||
tags: Vec::new(),
|
||||
parts: vec![PartRef { guid: old_chunk.guid, offset: 0, size: old_bytes.len() as u32 }],
|
||||
}],
|
||||
compress: true,
|
||||
meta_tail: Vec::new(),
|
||||
});
|
||||
fs::write(game.join("obsolete.bin"), old_bytes).unwrap();
|
||||
fs::write(metadata.join("installed.manifest"), &old_manifest).unwrap();
|
||||
let target_manifest = br#"{"ManifestFileVersion":"20","ChunkHashList":{},"FileManifestList":[]}"#;
|
||||
let target_path = metadata.join("target.manifest");
|
||||
fs::write(&target_path, target_manifest).unwrap();
|
||||
let mut req = request(&fx, &game);
|
||||
req.target_manifest_path = Some(target_path);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let ev = Recorder { refuse: true, ..Default::default() };
|
||||
let result = run(&req, &cancel, &ev);
|
||||
assert_eq!(result.unwrap_err(), Stop::Failed("The install record could not be switched to updating; nothing was replaced".into()));
|
||||
assert_eq!(ev.replaced.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(fs::read(game.join("obsolete.bin")).unwrap(), old_bytes);
|
||||
assert_eq!(fs::read(metadata.join("installed.manifest")).unwrap(), old_manifest);
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_run_reports_cancel() {
|
||||
let fx = fixture();
|
||||
@@ -267,7 +408,11 @@ fn a_cancelled_run_reports_cancel() {
|
||||
fn place_partial(fx: &Fixture, game: &Path, data: &[u8], list: &str) -> PathBuf {
|
||||
let stage = staging::recover(game).unwrap();
|
||||
let a = &fx.expected[0].1;
|
||||
let partial = stage.join(staging::partial_name("a.bin", 4000, Some(Sha1::digest(a).into())));
|
||||
let partial = stage.join(staging::partial_name(
|
||||
"a.bin",
|
||||
4000,
|
||||
Some(Sha1::digest(a).into()),
|
||||
));
|
||||
fs::write(&partial, data).unwrap();
|
||||
fs::write(staging::list_path(&partial), list).unwrap();
|
||||
partial
|
||||
@@ -285,7 +430,11 @@ fn a_paused_install_resumes_from_its_written_parts() {
|
||||
place_done_c(&fx, &game);
|
||||
place_partial(&fx, &game, &fx.expected[0].1[..3000], "0\n");
|
||||
let stage = game.join(staging::DIR_NAME);
|
||||
fs::write(stage.join(staging::partial_name("gone.bin", 9, None)), b"old").unwrap();
|
||||
fs::write(
|
||||
stage.join(staging::partial_name("gone.bin", 9, None)),
|
||||
b"old",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let events = Recorder::default();
|
||||
run(&request(&fx, &game), &AtomicBool::new(false), &events).unwrap();
|
||||
@@ -334,7 +483,12 @@ fn a_damaged_partial_fails_its_check_and_is_not_kept() {
|
||||
let fx = fixture();
|
||||
let game = temp_game("damagedpartial");
|
||||
place_partial(&fx, &game, &[0u8; 3000], "0\n");
|
||||
let err = run(&request(&fx, &game), &AtomicBool::new(false), &Recorder::default()).unwrap_err();
|
||||
let err = run(
|
||||
&request(&fx, &game),
|
||||
&AtomicBool::new(false),
|
||||
&Recorder::default(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(err, Stop::Failed("SHA-1 mismatch for a.bin".into()));
|
||||
assert!(staging::partials(&game.join(staging::DIR_NAME)).is_empty());
|
||||
let retry = Recorder::default();
|
||||
|
||||
@@ -182,10 +182,14 @@ impl<'a> Engine<'a> {
|
||||
let Some(handle) = handle else {
|
||||
return Err(format!("internal: {} is not open", file.path));
|
||||
};
|
||||
handle
|
||||
.write_all_at(piece, part.file_offset)
|
||||
.map_err(|e| format!("Could not assemble or atomically replace {}: {e}", file.path))?;
|
||||
self.written.fetch_add(piece.len() as u64, Ordering::Relaxed);
|
||||
handle.write_all_at(piece, part.file_offset).map_err(|e| {
|
||||
format!(
|
||||
"Could not assemble or atomically replace {}: {e}",
|
||||
file.path
|
||||
)
|
||||
})?;
|
||||
self.written
|
||||
.fetch_add(piece.len() as u64, Ordering::Relaxed);
|
||||
|
||||
let complete = {
|
||||
let mut slot = self.slots[f].lock().expect("slot lock");
|
||||
@@ -231,14 +235,21 @@ impl<'a> Engine<'a> {
|
||||
let (handle, stage, hash) = {
|
||||
let mut slot = self.slots[f].lock().expect("slot lock");
|
||||
slot.done = true;
|
||||
(slot.file.take(), slot.stage.clone(), slot.hasher.take().map(|h| -> Hash { h.finalize().into() }))
|
||||
(
|
||||
slot.file.take(),
|
||||
slot.stage.clone(),
|
||||
slot.hasher.take().map(|h| -> Hash { h.finalize().into() }),
|
||||
)
|
||||
};
|
||||
let stage = stage.ok_or_else(|| format!("internal: {} has no stage file", file.path))?;
|
||||
let result = (|| -> Result<(), String> {
|
||||
let handle = handle.ok_or_else(|| format!("internal: {} is not open", file.path))?;
|
||||
handle
|
||||
.sync_all()
|
||||
.map_err(|e| format!("Could not assemble or atomically replace {}: {e}", file.path))?;
|
||||
handle.sync_all().map_err(|e| {
|
||||
format!(
|
||||
"Could not assemble or atomically replace {}: {e}",
|
||||
file.path
|
||||
)
|
||||
})?;
|
||||
let len = handle.metadata().map(|m| m.len()).unwrap_or(u64::MAX);
|
||||
if len != file.size {
|
||||
return Err(format!("Size mismatch for {}", file.path));
|
||||
@@ -266,11 +277,19 @@ impl<'a> Engine<'a> {
|
||||
}
|
||||
}
|
||||
if let Some(parent) = file.dest.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|e| format!("Could not assemble or atomically replace {}: {e}", file.path))?;
|
||||
fs::create_dir_all(parent).map_err(|e| {
|
||||
format!(
|
||||
"Could not assemble or atomically replace {}: {e}",
|
||||
file.path
|
||||
)
|
||||
})?;
|
||||
}
|
||||
fs::rename(&stage, &file.dest)
|
||||
.map_err(|e| format!("Could not assemble or atomically replace {}: {e}", file.path))
|
||||
fs::rename(&stage, &file.dest).map_err(|e| {
|
||||
format!(
|
||||
"Could not assemble or atomically replace {}: {e}",
|
||||
file.path
|
||||
)
|
||||
})
|
||||
})();
|
||||
if file.resume.is_some() {
|
||||
let _ = fs::remove_file(staging::list_path(&stage));
|
||||
@@ -295,7 +314,10 @@ impl<'a> Engine<'a> {
|
||||
fn open_stage(&self, f: usize) -> Result<(), String> {
|
||||
let file = &self.input.files[f];
|
||||
let (path, opened) = match &file.resume {
|
||||
Some(r) => (r.stage.clone(), OpenOptions::new().read(true).write(true).open(&r.stage)),
|
||||
Some(r) => (
|
||||
r.stage.clone(),
|
||||
OpenOptions::new().read(true).write(true).open(&r.stage),
|
||||
),
|
||||
None => {
|
||||
let path = self.input.stage_dir.join(staging::unique_name());
|
||||
let opened = OpenOptions::new().read(true).write(true).create_new(true).open(&path);
|
||||
@@ -397,8 +419,12 @@ impl<'a> Engine<'a> {
|
||||
producer.uses.iter().any(|&u| schedule.use_file[u as usize] as usize >= c.next_file)
|
||||
};
|
||||
if needs_cache {
|
||||
cache::store(&self.input.cache_dir, &cache::entry_name(info, producer.copy), &data)
|
||||
.map_err(|e| SinkError::Fatal(self.fail(e)))?;
|
||||
cache::store(
|
||||
&self.input.cache_dir,
|
||||
&cache::entry_name(info, producer.copy),
|
||||
&data,
|
||||
)
|
||||
.map_err(|e| SinkError::Fatal(self.fail(e)))?;
|
||||
}
|
||||
let claims: Vec<usize> = {
|
||||
let mut c = self.coord.lock().expect("coord lock");
|
||||
@@ -521,7 +547,12 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
|
||||
stream: false,
|
||||
};
|
||||
|
||||
events.progress(input.progress_base, engine.total_bytes, 0, input.files.len() as u32);
|
||||
events.progress(
|
||||
input.progress_base,
|
||||
engine.total_bytes,
|
||||
0,
|
||||
input.files.len() as u32,
|
||||
);
|
||||
let log = |line: &str| events.log(line);
|
||||
let gate = |i: usize| -> bool {
|
||||
engine.hint.fetch_max(i, Ordering::Relaxed);
|
||||
@@ -546,7 +577,16 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
|
||||
let outcome = if items.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(run_fetch_gated(items, &hosts, &options, &Sink(&engine), stop, &|_: u64, _: u64| {}, &log, &gate))
|
||||
Some(run_fetch_gated(
|
||||
items,
|
||||
&hosts,
|
||||
&options,
|
||||
&Sink(&engine),
|
||||
stop,
|
||||
&|_: u64, _: u64| {},
|
||||
&log,
|
||||
&gate,
|
||||
))
|
||||
};
|
||||
{
|
||||
let mut c = engine.coord.lock().expect("coord lock");
|
||||
@@ -597,7 +637,10 @@ fetches={} refetches={} peak_cache_mib={} hosts={}",
|
||||
return Err(Stop::Failed(message));
|
||||
}
|
||||
if complete {
|
||||
return Ok(Stats { bytes_written: written, files_written: input.files.len() });
|
||||
return Ok(Stats {
|
||||
bytes_written: written,
|
||||
files_written: input.files.len(),
|
||||
});
|
||||
}
|
||||
if let Some(message) = fetch_error {
|
||||
return Err(Stop::Failed(format!("Download failed: {}", tidy_fetch_error(&message))));
|
||||
@@ -605,7 +648,9 @@ fetches={} refetches={} peak_cache_mib={} hosts={}",
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
return Err(Stop::Cancelled);
|
||||
}
|
||||
Err(Stop::Failed("The download ended before every file was written".into()))
|
||||
Err(Stop::Failed(
|
||||
"The download ended before every file was written".into(),
|
||||
))
|
||||
}
|
||||
|
||||
fn hash_whole(handle: &File, file: &EngineFile) -> Result<Hash, String> {
|
||||
@@ -624,8 +669,18 @@ fn hash_whole(handle: &File, file: &EngineFile) -> Result<Hash, String> {
|
||||
}
|
||||
|
||||
fn keep_partial(file: &EngineFile, written: &[bool], stage: &Path, dir: &Path) -> bool {
|
||||
let mut kept: Vec<u64> = file.resume.as_ref().map(|r| r.kept.clone()).unwrap_or_default();
|
||||
kept.extend(file.parts.iter().zip(written).filter(|(_, w)| **w).map(|(p, _)| p.file_offset));
|
||||
let mut kept: Vec<u64> = file
|
||||
.resume
|
||||
.as_ref()
|
||||
.map(|r| r.kept.clone())
|
||||
.unwrap_or_default();
|
||||
kept.extend(
|
||||
file.parts
|
||||
.iter()
|
||||
.zip(written)
|
||||
.filter(|(_, w)| **w)
|
||||
.map(|(p, _)| p.file_offset),
|
||||
);
|
||||
if kept.is_empty() || file.sha1.is_none() {
|
||||
return false;
|
||||
}
|
||||
@@ -657,7 +712,12 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn part(file_offset: u64, size: u32) -> PlanPart {
|
||||
PlanPart { chunk: 0, chunk_offset: 0, size, file_offset }
|
||||
PlanPart {
|
||||
chunk: 0,
|
||||
chunk_offset: 0,
|
||||
size,
|
||||
file_offset,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -697,7 +757,10 @@ mod tests {
|
||||
|
||||
let resumed = EngineFile {
|
||||
parts: vec![part(0, 10)],
|
||||
resume: Some(Resume { stage: kept.clone(), kept: vec![20, 10] }),
|
||||
resume: Some(Resume {
|
||||
stage: kept.clone(),
|
||||
kept: vec![20, 10],
|
||||
}),
|
||||
..file
|
||||
};
|
||||
assert!(keep_partial(&resumed, &[false], &kept, &dir));
|
||||
|
||||
@@ -2,7 +2,9 @@ use serde_json::{json, Value};
|
||||
|
||||
use super::build_info::{self, BuildInfo};
|
||||
use super::net::str_of;
|
||||
use super::{account, achievements, catalog, install, launch, library, locale, manifest, savesync, shop};
|
||||
use super::{
|
||||
account, achievements, catalog, install, launch, library, locale, manifest, savesync, shop,
|
||||
};
|
||||
|
||||
fn error(message: impl Into<String>) -> Value {
|
||||
json!({ "error": message.into() })
|
||||
@@ -45,10 +47,16 @@ fn dispatch(op: &str, req: &Value) -> Value {
|
||||
Ok(list) => json!({ "records": list.iter().map(|o| json!({
|
||||
"appName": o.app_name, "namespace": o.namespace, "catalogItemId": o.catalog_item_id,
|
||||
})).collect::<Vec<_>>() }),
|
||||
Err(library::ListError::SignIn) => json!({ "error": "sign-in refused", "signIn": true }),
|
||||
Err(library::ListError::SignIn) => {
|
||||
json!({ "error": "sign-in refused", "signIn": true })
|
||||
}
|
||||
Err(library::ListError::Failed(e)) => error(e),
|
||||
},
|
||||
"catalog.details" => match catalog::details(token, str_of(req, "namespace"), str_of(req, "catalogItemId")) {
|
||||
"catalog.details" => match catalog::details(
|
||||
token,
|
||||
str_of(req, "namespace"),
|
||||
str_of(req, "catalogItemId"),
|
||||
) {
|
||||
Some(d) => json!({ "details": d }),
|
||||
None => error("no catalog answer"),
|
||||
},
|
||||
@@ -70,9 +78,13 @@ fn dispatch(op: &str, req: &Value) -> Value {
|
||||
Some(info) => json!({ "info": info.to_json() }),
|
||||
None => error("The manifest could not be fetched"),
|
||||
},
|
||||
"build.cdns" => json!({ "cdns": info_of(req).map(|i| build_info::cdns_to_json(&i.cdns)).unwrap_or(json!([])) }),
|
||||
"build.cdns" => {
|
||||
json!({ "cdns": info_of(req).map(|i| build_info::cdns_to_json(&i.cdns)).unwrap_or(json!([])) })
|
||||
}
|
||||
"build.prereq" => match info_of(req).map(|i| install::fetch_manifest(&i, &|_: &str| {})) {
|
||||
Some(Ok(m)) => json!({ "name": m.prereq_name, "path": m.prereq_path, "read": m.prereq_read }),
|
||||
Some(Ok(m)) => {
|
||||
json!({ "name": m.prereq_name, "path": m.prereq_path, "read": m.prereq_read })
|
||||
}
|
||||
Some(Err(e)) => error(e),
|
||||
None => error("no build information"),
|
||||
},
|
||||
@@ -86,17 +98,29 @@ fn dispatch(op: &str, req: &Value) -> Value {
|
||||
Some(list) => json!({ "list": list }),
|
||||
None => error("unreachable"),
|
||||
},
|
||||
"cloud.list" => match savesync::list(token, str_of(req, "accountId"), str_of(req, "appName")) {
|
||||
Ok(files) => json!({ "files": files }),
|
||||
Err(e) => error(e),
|
||||
},
|
||||
"cloud.list" => {
|
||||
match savesync::list(token, str_of(req, "accountId"), str_of(req, "appName")) {
|
||||
Ok(files) => json!({ "files": files }),
|
||||
Err(e) => error(e),
|
||||
}
|
||||
}
|
||||
"cloud.writeLinks" => {
|
||||
let names: Vec<String> = req
|
||||
.get("names")
|
||||
.and_then(|n| n.as_array())
|
||||
.map(|a| a.iter().filter_map(|n| n.as_str()).map(str::to_string).collect())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|n| n.as_str())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
match savesync::write_links(token, str_of(req, "accountId"), str_of(req, "appName"), &names) {
|
||||
match savesync::write_links(
|
||||
token,
|
||||
str_of(req, "accountId"),
|
||||
str_of(req, "appName"),
|
||||
&names,
|
||||
) {
|
||||
Ok(links) => json!({ "links": links }),
|
||||
Err(e) => error(e),
|
||||
}
|
||||
@@ -154,11 +178,42 @@ pub fn inspect(bytes: &[u8], request: &str) -> String {
|
||||
Err(e) => return error(e).to_string(),
|
||||
};
|
||||
let out = match str_of(&req, "op") {
|
||||
"estimate" => {
|
||||
let tags: Option<Vec<String>> = req.get("tags").and_then(|t| t.as_array()).map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|t| t.as_str())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
});
|
||||
let selected = locale::select(&m.files, tags.as_deref());
|
||||
let mut chunks = std::collections::HashSet::new();
|
||||
let mut disk_bytes = 0u64;
|
||||
for &i in &selected {
|
||||
let file = &m.files[i];
|
||||
disk_bytes = disk_bytes.saturating_add(file.size);
|
||||
for part in &file.parts {
|
||||
if let Some(&chunk) = m.chunk_index.get(&part.guid) {
|
||||
chunks.insert(chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
let download_bytes: u64 = chunks.iter().fold(0u64, |sum, &i| {
|
||||
let chunk = &m.chunks[i];
|
||||
sum.saturating_add(if chunk.cdn_size > 0 {
|
||||
chunk.cdn_size
|
||||
} else {
|
||||
chunk.window as u64
|
||||
})
|
||||
});
|
||||
json!({ "files": selected.len(), "chunks": chunks.len(), "downloadBytes": download_bytes, "diskBytes": disk_bytes })
|
||||
}
|
||||
"select" => {
|
||||
let tags: Option<Vec<String>> = req
|
||||
.get("tags")
|
||||
.and_then(|t| t.as_array())
|
||||
.map(|a| a.iter().filter_map(|t| t.as_str()).map(str::to_string).collect());
|
||||
let tags: Option<Vec<String>> = req.get("tags").and_then(|t| t.as_array()).map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|t| t.as_str())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
});
|
||||
json!({ "indices": locale::select(&m.files, tags.as_deref()) })
|
||||
}
|
||||
"launch" => json!({
|
||||
@@ -187,13 +242,21 @@ mod tests {
|
||||
let v: Value = serde_json::from_str(&call("locale", r#"{"language":"pt","region":"BR"}"#)).unwrap();
|
||||
assert_eq!(v["key"], "pt-BR");
|
||||
assert_eq!(v["launchLocale"], "pt");
|
||||
let v: Value = serde_json::from_str(&call("auth.codeFromPage", r#"{"text":"{\"authorizationCode\":\"c1\"}"}"#)).unwrap();
|
||||
let v: Value = serde_json::from_str(&call(
|
||||
"auth.codeFromPage",
|
||||
r#"{"text":"{\"authorizationCode\":\"c1\"}"}"#,
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(v["code"], "c1");
|
||||
let v: Value = serde_json::from_str(&call("nope", "{}")).unwrap();
|
||||
assert!(v["error"].is_string());
|
||||
let v: Value = serde_json::from_str(&call("launch.args", r#"{"namespace":"ns","appName":"A"}"#)).unwrap();
|
||||
assert_eq!(v["args"][0], "-EpicPortal");
|
||||
let v: Value = serde_json::from_str(&call("launch.split", r#"{"command":"-PCStore=EGS \"-log=a b.txt\""}"#)).unwrap();
|
||||
let v: Value = serde_json::from_str(&call(
|
||||
"launch.split",
|
||||
r#"{"command":"-PCStore=EGS \"-log=a b.txt\""}"#,
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(v["args"], json!(["-PCStore=EGS", "-log=a b.txt"]));
|
||||
}
|
||||
|
||||
@@ -207,8 +270,18 @@ mod tests {
|
||||
prereq: None,
|
||||
chunks: vec![],
|
||||
files: vec![
|
||||
TestFile { path: "x.exe".into(), sha1: [0; 20], tags: vec![], parts: vec![] },
|
||||
TestFile { path: "de.pak".into(), sha1: [0; 20], tags: vec!["German".into()], parts: vec![] },
|
||||
TestFile {
|
||||
path: "x.exe".into(),
|
||||
sha1: [0; 20],
|
||||
tags: vec![],
|
||||
parts: vec![],
|
||||
},
|
||||
TestFile {
|
||||
path: "de.pak".into(),
|
||||
sha1: [0; 20],
|
||||
tags: vec!["German".into()],
|
||||
parts: vec![],
|
||||
},
|
||||
],
|
||||
compress: false,
|
||||
meta_tail: vec![],
|
||||
@@ -225,4 +298,47 @@ mod tests {
|
||||
let v: Value = serde_json::from_str(&inspect(b"nonsense", "{}")).unwrap();
|
||||
assert!(v["error"].is_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimate_counts_unique_chunks_and_selected_disk_bytes() {
|
||||
use crate::epic::manifest::{
|
||||
testing::{build, chunk, TestFile, TestManifest},
|
||||
PartRef,
|
||||
};
|
||||
let chunk = chunk(50, 4);
|
||||
let part = PartRef {
|
||||
guid: chunk.guid,
|
||||
offset: 0,
|
||||
size: 4,
|
||||
};
|
||||
let manifest = TestManifest {
|
||||
version: 21,
|
||||
build: "1".into(),
|
||||
exe: "Game.exe".into(),
|
||||
prereq: None,
|
||||
chunks: vec![chunk],
|
||||
files: vec![
|
||||
TestFile {
|
||||
path: "a.bin".into(),
|
||||
sha1: [1; 20],
|
||||
tags: vec![],
|
||||
parts: vec![part],
|
||||
},
|
||||
TestFile {
|
||||
path: "b.bin".into(),
|
||||
sha1: [2; 20],
|
||||
tags: vec![],
|
||||
parts: vec![part],
|
||||
},
|
||||
],
|
||||
compress: false,
|
||||
meta_tail: Vec::new(),
|
||||
};
|
||||
let response: Value =
|
||||
serde_json::from_str(&inspect(&build(&manifest), r#"{"op":"estimate"}"#)).unwrap();
|
||||
assert_eq!(response["files"], 2);
|
||||
assert_eq!(response["chunks"], 1);
|
||||
assert_eq!(response["downloadBytes"], 1000);
|
||||
assert_eq!(response["diskBytes"], 8);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
pub mod engine;
|
||||
pub mod jni;
|
||||
pub mod plan;
|
||||
pub mod maintenance;
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
#include "xdelta3.h"
|
||||
|
||||
typedef struct { size_t used; } dd_budget;
|
||||
typedef struct { size_t size; } dd_allocation;
|
||||
|
||||
static void *dd_alloc(void *opaque, size_t count, usize_t size) {
|
||||
dd_budget *budget = opaque;
|
||||
if (size && count > (62u * 1024u * 1024u) / size) return NULL;
|
||||
size_t n = count * size;
|
||||
if (n > 62u * 1024u * 1024u - budget->used) return NULL;
|
||||
dd_allocation *allocation = malloc(sizeof(*allocation) + n);
|
||||
if (!allocation) return NULL;
|
||||
allocation->size = n;
|
||||
budget->used += n;
|
||||
return allocation + 1;
|
||||
}
|
||||
|
||||
static void dd_free(void *opaque, void *ptr) {
|
||||
if (!ptr) return;
|
||||
dd_allocation *allocation = (dd_allocation *)ptr - 1;
|
||||
((dd_budget *)opaque)->used -= allocation->size;
|
||||
free(allocation);
|
||||
}
|
||||
|
||||
int dd_gog_delta(const char *source, const char *patch, const char *target,
|
||||
int (*cancel)(void *), void *opaque) {
|
||||
FILE *old = NULL, *delta = NULL, *out = NULL;
|
||||
xd3_stream stream = {0};
|
||||
xd3_source src = {0};
|
||||
xd3_config config = {0};
|
||||
dd_budget budget = {0};
|
||||
unsigned char *input = NULL, *block = NULL;
|
||||
int result = -1, configured = 0;
|
||||
old = fopen(source, "rb"); delta = fopen(patch, "rb"); out = fopen(target, "wb");
|
||||
if (!old || !delta || !out) goto done;
|
||||
input = malloc(64 * 1024); block = malloc(1024 * 1024);
|
||||
if (!input || !block) goto done;
|
||||
config.winsize = 64 * 1024;
|
||||
config.alloc = dd_alloc; config.freef = dd_free; config.opaque = &budget;
|
||||
if (xd3_config_stream(&stream, &config)) goto done;
|
||||
configured = 1;
|
||||
src.blksize = 1024 * 1024; src.curblk = block; src.curblkno = 0;
|
||||
src.onblk = fread(block, 1, src.blksize, old);
|
||||
if (xd3_set_source(&stream, &src)) goto done;
|
||||
for (;;) {
|
||||
size_t n = fread(input, 1, 64 * 1024, delta);
|
||||
if (ferror(delta)) goto done;
|
||||
if (feof(delta)) xd3_set_flags(&stream, XD3_FLUSH);
|
||||
xd3_avail_input(&stream, input, n);
|
||||
int code;
|
||||
while ((code = xd3_decode_input(&stream)) != XD3_INPUT) {
|
||||
if (cancel && cancel(opaque)) { result = 130; goto done; }
|
||||
switch (code) {
|
||||
case XD3_OUTPUT:
|
||||
if (fwrite(stream.next_out, 1, stream.avail_out, out) != stream.avail_out) goto done;
|
||||
xd3_consume_output(&stream); break;
|
||||
case XD3_GETSRCBLK:
|
||||
if (fseeko(old, (off_t)(src.getblkno * src.blksize), SEEK_SET)) goto done;
|
||||
src.curblkno = src.getblkno;
|
||||
src.onblk = fread(block, 1, src.blksize, old);
|
||||
if (ferror(old)) goto done;
|
||||
break;
|
||||
case XD3_GOTHEADER: case XD3_WINSTART: case XD3_WINFINISH: break;
|
||||
default: goto done;
|
||||
}
|
||||
}
|
||||
if (feof(delta)) break;
|
||||
}
|
||||
if (xd3_close_stream(&stream) || fflush(out)) goto done;
|
||||
result = 0;
|
||||
done:
|
||||
if (configured) xd3_free_stream(&stream);
|
||||
if (old) fclose(old);
|
||||
if (delta) fclose(delta);
|
||||
if (out && fclose(out)) result = -1;
|
||||
free(input); free(block);
|
||||
return result;
|
||||
}
|
||||
@@ -32,11 +32,14 @@ pub enum PlanKind {
|
||||
#[default]
|
||||
Gen2Chunks,
|
||||
Gen1Ranges,
|
||||
Maintenance,
|
||||
}
|
||||
|
||||
impl PlanKind {
|
||||
pub fn from_i32(v: i32) -> Self {
|
||||
if v == 1 {
|
||||
if v == 2 {
|
||||
PlanKind::Maintenance
|
||||
} else if v == 1 {
|
||||
PlanKind::Gen1Ranges
|
||||
} else {
|
||||
PlanKind::Gen2Chunks
|
||||
@@ -72,6 +75,7 @@ pub trait GogEvents: Sync {
|
||||
);
|
||||
fn on_log(&self, line: &str);
|
||||
fn on_bytes(&self, _bytes_done: u64, _bytes_total: u64) {}
|
||||
fn on_maintenance(&self, _network_bytes: u64, _reused_bytes: u64, _applied_bytes: u64) {}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
@@ -672,6 +676,7 @@ pub fn run(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Gog
|
||||
match req.kind {
|
||||
PlanKind::Gen2Chunks => run_gen2(req, cancel, events),
|
||||
PlanKind::Gen1Ranges => run_gen1(req, cancel, events),
|
||||
PlanKind::Maintenance => super::maintenance::run(req, cancel, events),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
@@ -153,6 +153,15 @@ impl GogEvents for JniEvents {
|
||||
let _ = env.delete_local_ref(text);
|
||||
});
|
||||
}
|
||||
|
||||
fn on_maintenance(&self, network_bytes: u64, reused_bytes: u64, applied_bytes: u64) {
|
||||
self.with_env(|env| {
|
||||
let _ = env.call_method(self.listener.as_obj(), "onMaintenance", "(JJJ)V", &[
|
||||
JValue::Long(network_bytes as jlong), JValue::Long(reused_bytes as jlong), JValue::Long(applied_bytes as jlong),
|
||||
]);
|
||||
Self::clear_exception(env);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn jstring_to_string(env: &mut JNIEnv, value: &JString) -> Option<String> {
|
||||
@@ -197,7 +206,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_gog_GogNative_nativePr
|
||||
_env: JNIEnv,
|
||||
_class: JClass,
|
||||
) -> jint {
|
||||
1
|
||||
2
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
|
||||
@@ -0,0 +1,523 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ffi::CString;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use serde_json::Value;
|
||||
use super::engine::{GogEvents, GogRequest, GogRunResult, http_status_in, is_link_expiry_status};
|
||||
use super::{md5_hex, md5_hex_file};
|
||||
|
||||
static DELTA_LOCK: Mutex<()> = Mutex::new(());
|
||||
unsafe extern "C" {
|
||||
fn dd_gog_delta(source: *const libc::c_char, patch: *const libc::c_char, target: *const libc::c_char,
|
||||
cancel: extern "C" fn(*mut libc::c_void) -> libc::c_int, opaque: *mut libc::c_void) -> libc::c_int;
|
||||
}
|
||||
extern "C" fn cancelled(opaque: *mut libc::c_void) -> libc::c_int {
|
||||
unsafe { (*(opaque as *const AtomicBool)).load(Ordering::Relaxed) as libc::c_int }
|
||||
}
|
||||
|
||||
fn http_client(read_timeout: std::time::Duration) -> Result<reqwest::Client, String> {
|
||||
reqwest::Client::builder()
|
||||
.connect_timeout(std::time::Duration::from_secs(20))
|
||||
.read_timeout(read_timeout)
|
||||
.build().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn inside(root: &Path, relative: &str) -> Result<PathBuf, String> {
|
||||
if relative.is_empty() || relative.contains(['\\', ':', '\0']) || relative.split('/').any(|p| p.is_empty() || p == "." || p == "..") { return Err("invalid GOG path".into()); }
|
||||
let mut out = root.to_path_buf();
|
||||
for component in Path::new(relative).components() {
|
||||
let Component::Normal(part) = component else { return Err("GOG path leaves installation".into()) };
|
||||
out.push(part);
|
||||
if fs::symlink_metadata(&out).map(|m| m.file_type().is_symlink()).unwrap_or(false) {
|
||||
return Err("GOG path is a symbolic link".into());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn text<'a>(v: &'a Value, key: &str) -> &'a str { v.get(key).and_then(Value::as_str).unwrap_or("") }
|
||||
fn num(v: &Value, key: &str) -> u64 { v.get(key).and_then(Value::as_u64).unwrap_or(0) }
|
||||
fn array<'a>(v: &'a Value, key: &str) -> &'a [Value] { v.get(key).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) }
|
||||
fn valid_md5(s: &str) -> bool { s.len() == 32 && s.bytes().all(|c| c.is_ascii_hexdigit()) }
|
||||
|
||||
fn matches(path: &Path, file: &Value) -> bool {
|
||||
if !fs::metadata(path).map(|m| m.is_file() && m.len() == num(file, "size")).unwrap_or(false) { return false; }
|
||||
let md5 = text(file, "md5");
|
||||
if valid_md5(md5) { return md5_hex_file(path).map(|h| h.eq_ignore_ascii_case(md5)).unwrap_or(false); }
|
||||
let sha = text(file, "sha256");
|
||||
if sha.len() == 64 {
|
||||
use sha2::{Digest, Sha256};
|
||||
let Ok(mut input) = File::open(path) else { return false; };
|
||||
let mut digest = Sha256::new(); let mut buffer = [0u8; 64 * 1024];
|
||||
loop { let Ok(n) = input.read(&mut buffer) else { return false; }; if n == 0 { break; } digest.update(&buffer[..n]); }
|
||||
return super::to_hex(&digest.finalize()).eq_ignore_ascii_case(sha);
|
||||
}
|
||||
let chunks = array(file, "chunks");
|
||||
if chunks.is_empty() { return num(file, "size") == 0; }
|
||||
let Ok(mut input) = File::open(path) else { return false; };
|
||||
chunks.iter().all(|chunk| {
|
||||
let size = num(chunk, "size");
|
||||
valid_md5(text(chunk, "md5")) && hash_range(&mut input, size).as_deref() == Some(text(chunk, "md5"))
|
||||
})
|
||||
}
|
||||
|
||||
fn hash_range(input: &mut File, size: u64) -> Option<String> {
|
||||
let mut digest = crate::md5_small::Md5::new();
|
||||
let mut remaining = size;
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
while remaining > 0 {
|
||||
let want = remaining.min(buffer.len() as u64) as usize;
|
||||
input.read_exact(&mut buffer[..want]).ok()?;
|
||||
digest.update(&buffer[..want]); remaining -= want as u64;
|
||||
}
|
||||
Some(super::to_hex(&digest.finalize()))
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Reuse { path: PathBuf, offset: u64, size: u64 }
|
||||
type ReuseMap = HashMap<(String, u64), Vec<Reuse>>;
|
||||
|
||||
fn reuse_map(root: &Path, files: &[Value]) -> Result<ReuseMap, String> {
|
||||
let mut result: ReuseMap = HashMap::new();
|
||||
for file in files {
|
||||
if text(file, "path").to_lowercase().starts_with(".droiddeck-") { return Err("GOG content overlaps launcher metadata".into()); }
|
||||
let path = inside(root, text(file, "path"))?;
|
||||
let mut offset: u64 = 0;
|
||||
for chunk in array(file, "chunks") {
|
||||
let size = num(chunk, "size");
|
||||
if valid_md5(text(chunk, "md5")) {
|
||||
result.entry((text(chunk, "md5").to_ascii_lowercase(), size)).or_default()
|
||||
.push(Reuse { path: path.clone(), offset, size });
|
||||
}
|
||||
offset = offset.checked_add(size).ok_or("GOG file size overflow")?;
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn reusable(chunk: &Value, map: &ReuseMap) -> Option<Reuse> {
|
||||
let key = (text(chunk, "md5").to_ascii_lowercase(), num(chunk, "size"));
|
||||
map.get(&key)?.iter().find(|old| {
|
||||
let Ok(mut file) = File::open(&old.path) else { return false; };
|
||||
file.seek(SeekFrom::Start(old.offset)).is_ok() && hash_range(&mut file, old.size).map(|h| h.eq_ignore_ascii_case(&key.0)).unwrap_or(false)
|
||||
}).cloned()
|
||||
}
|
||||
|
||||
struct Transfer<'a> {
|
||||
runtime: tokio::runtime::Runtime,
|
||||
client: reqwest::Client,
|
||||
cancel: &'a AtomicBool,
|
||||
events: &'a dyn GogEvents,
|
||||
wire: u64,
|
||||
total: u64,
|
||||
}
|
||||
|
||||
impl Transfer<'_> {
|
||||
fn fetch(&mut self, urls: &[String], range: Option<(u64, u64)>, dest: &Path, limit: u64) -> Result<(), String> {
|
||||
let mut failure = "GOG download has no URLs".to_string();
|
||||
for _ in 0..3 {
|
||||
for url in urls {
|
||||
if self.cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
let result = self.runtime.block_on(async {
|
||||
let mut request = self.client.get(url).header("User-Agent", "GOG Galaxy");
|
||||
if let Some((start, end)) = range { request = request.header("Range", format!("bytes={start}-{end}")); }
|
||||
let mut response = request.send().await.map_err(|_| "GOG connection failed".to_string())?;
|
||||
let status = response.status().as_u16();
|
||||
if status != if range.is_some() { 206 } else { 200 } { return Err(format!("HTTP {status}")); }
|
||||
let mut output = File::create(dest).map_err(|e| e.to_string())?;
|
||||
let mut size = 0u64;
|
||||
while let Some(bytes) = response.chunk().await.map_err(|_| "GOG connection interrupted".to_string())? {
|
||||
if self.cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
size += bytes.len() as u64;
|
||||
if limit > 0 && size > limit { return Err("GOG response exceeds expected size".into()); }
|
||||
self.wire += bytes.len() as u64;
|
||||
self.events.on_bytes(self.wire, self.total.max(self.wire));
|
||||
output.write_all(&bytes).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if limit > 0 && size != limit { return Err("GOG download is incomplete".into()); }
|
||||
output.sync_all().map_err(|e| e.to_string())
|
||||
});
|
||||
match result { Ok(()) => return Ok(()), Err(e) => failure = e }
|
||||
if http_status_in(&failure).map(is_link_expiry_status).unwrap_or(false) { return Err(failure); }
|
||||
}
|
||||
}
|
||||
Err(failure)
|
||||
}
|
||||
}
|
||||
|
||||
fn urls(links: &Value, product: &str, suffix: &str) -> Vec<String> {
|
||||
links.get(product).and_then(Value::as_array).map(|bases| bases.iter().filter_map(Value::as_str).map(|base| {
|
||||
if base.contains("{GALAXY_PATH}") { base.replace("{GALAXY_PATH}", suffix) }
|
||||
else if let Some((path, query)) = base.split_once('?') { format!("{}{suffix}?{query}", path.trim_end_matches('/').to_string() + "/") }
|
||||
else { format!("{}{suffix}", base.trim_end_matches('/').to_string() + "/") }
|
||||
}).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn chunk_path(chunk: &Value) -> Result<String, String> {
|
||||
let hash = text(chunk, "compressedMd5");
|
||||
if !valid_md5(hash) { return Err("GOG chunk has no valid compressed hash".into()); }
|
||||
Ok(super::plan::build_cdn_path(hash))
|
||||
}
|
||||
|
||||
fn download_chunk(transfer: &mut Transfer, links: &Value, product: &str, chunk: &Value, scratch: &Path, output: &mut File) -> Result<(), String> {
|
||||
transfer.fetch(&urls(links, product, &chunk_path(chunk)?), None, scratch, num(chunk, "compressedSize"))?;
|
||||
if !md5_hex_file(scratch).map(|h| h.eq_ignore_ascii_case(text(chunk, "compressedMd5"))).unwrap_or(false) { return Err("GOG compressed chunk checksum mismatch".into()); }
|
||||
let mut raw = File::open(scratch).map_err(|e| e.to_string())?;
|
||||
let mut head = [0u8; 1]; raw.read_exact(&mut head).map_err(|e| e.to_string())?;
|
||||
raw.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
|
||||
let stored = num(chunk, "size") == num(chunk, "compressedSize") && text(chunk, "md5").eq_ignore_ascii_case(text(chunk, "compressedMd5"));
|
||||
let input: Box<dyn Read> = if !stored && head[0] == 0x78 { Box::new(flate2::read::ZlibDecoder::new(raw)) } else { Box::new(raw) };
|
||||
let mut input = input.take(num(chunk, "size") + 1);
|
||||
let mut digest = crate::md5_small::Md5::new();
|
||||
let mut size = 0u64;
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
loop {
|
||||
let n = input.read(&mut buffer).map_err(|_| "GOG chunk decompression failed")?;
|
||||
if n == 0 { break; }
|
||||
if transfer.cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
digest.update(&buffer[..n]); size += n as u64;
|
||||
output.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if size != num(chunk, "size") || !super::to_hex(&digest.finalize()).eq_ignore_ascii_case(text(chunk, "md5")) { return Err("GOG chunk checksum mismatch".into()); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_delta(root: &Path, file: &Value, patch: &Value, plan: &Value, stage: &Path, transfer: &mut Transfer) -> Result<(), String> {
|
||||
let _guard = DELTA_LOCK.lock().map_err(|_| "GOG delta lock poisoned")?;
|
||||
let source = inside(root, &text(patch, "path_source").replace('\\', "/"))?;
|
||||
if !md5_hex_file(&source).map(|h| h.eq_ignore_ascii_case(text(patch, "md5_source"))).unwrap_or(false) { return Err("GOG delta source changed".into()); }
|
||||
let payload = stage.with_extension("delta");
|
||||
let packed = stage.with_extension("packed");
|
||||
let mut output = File::create(&payload).map_err(|e| e.to_string())?;
|
||||
for chunk in array(patch, "chunks") { download_chunk(transfer, &plan["patchLinks"], text(patch, "product"), chunk, &packed, &mut output)?; }
|
||||
drop(output);
|
||||
if !md5_hex_file(&payload).map(|h| h.eq_ignore_ascii_case(text(patch, "md5"))).unwrap_or(false) { return Err("GOG delta checksum mismatch".into()); }
|
||||
let cpath = |p: &Path| CString::new(p.as_os_str().as_encoded_bytes()).map_err(|_| "invalid path");
|
||||
let (s, p, t) = (cpath(&source)?, cpath(&payload)?, cpath(stage)?);
|
||||
let code = unsafe { dd_gog_delta(s.as_ptr(), p.as_ptr(), t.as_ptr(), cancelled, transfer.cancel as *const AtomicBool as *mut libc::c_void) };
|
||||
let _ = fs::remove_file(payload); let _ = fs::remove_file(packed);
|
||||
if code != 0 || !matches(stage, file) || !md5_hex_file(stage).map(|h| h.eq_ignore_ascii_case(text(patch, "md5_target"))).unwrap_or(false) { return Err("GOG delta reconstruction failed".into()); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn run(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> GogRunResult {
|
||||
let mut result = GogRunResult::default();
|
||||
let work = || -> Result<(u64, u32), String> {
|
||||
let plan: Value = serde_json::from_str(req.depot_manifests.first().ok_or("missing GOG maintenance plan")?).map_err(|_| "invalid GOG maintenance plan")?;
|
||||
let root = fs::canonicalize(&req.install_dir).map_err(|e| e.to_string())?;
|
||||
let files = array(&plan, "files");
|
||||
let mut seen = HashSet::new();
|
||||
let mut components = HashMap::new();
|
||||
for file in files {
|
||||
let name = text(file, "path"); inside(&root, name)?;
|
||||
if name.to_lowercase().starts_with(".droiddeck-") || !seen.insert(name.to_lowercase()) { return Err("ambiguous GOG path".into()); }
|
||||
let mut parent = root.clone();
|
||||
let mut relative = PathBuf::new();
|
||||
for part in name.split('/') {
|
||||
relative.push(part);
|
||||
let key = relative.to_string_lossy().to_lowercase();
|
||||
if let Some(previous) = components.insert(key, relative.clone()) {
|
||||
if previous != relative { return Err("ambiguous GOG directory".into()); }
|
||||
}
|
||||
if let Ok(entries) = fs::read_dir(&parent) {
|
||||
for entry in entries.flatten() {
|
||||
let actual = entry.file_name().to_string_lossy().into_owned();
|
||||
if actual != part && actual.to_lowercase() == part.to_lowercase() { return Err("existing path differs only by case".into()); }
|
||||
}
|
||||
}
|
||||
parent.push(part);
|
||||
}
|
||||
}
|
||||
let map = reuse_map(&root, array(&plan, "oldFiles"))?;
|
||||
let stages = inside(&root, ".droiddeck-gog/stage")?;
|
||||
fs::create_dir_all(&stages).map_err(|e| e.to_string())?;
|
||||
let mut transfer = Transfer {
|
||||
runtime: tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| e.to_string())?,
|
||||
client: http_client(std::time::Duration::from_secs(60))?,
|
||||
cancel, events, wire: 0, total: num(&plan, "downloadBytes"),
|
||||
};
|
||||
let mut done = 0u32; let mut reused = 0u64; let mut applied = 0u64;
|
||||
for file in files {
|
||||
if cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
let path = inside(&root, text(file, "path"))?;
|
||||
if file.get("directory").and_then(Value::as_bool).unwrap_or(false) {
|
||||
fs::create_dir_all(&path).map_err(|e| e.to_string())?; done += 1; continue;
|
||||
}
|
||||
if matches(&path, file) { done += 1; events.on_file_done(text(file, "path"), num(file, "size"), true, done, files.len() as u32, transfer.wire, transfer.total); continue; }
|
||||
let stage = stages.join(md5_hex(text(file, "path").as_bytes()));
|
||||
if !matches(&stage, file) {
|
||||
let mut start = 0;
|
||||
let missing_bytes: u64 = array(file, "chunks").iter().map(|chunk| {
|
||||
let valid = File::open(&stage).ok().map(|mut input| input.seek(SeekFrom::Start(start)).is_ok() &&
|
||||
hash_range(&mut input, num(chunk, "size")).map(|h| h.eq_ignore_ascii_case(text(chunk, "md5"))).unwrap_or(false)).unwrap_or(false);
|
||||
start += num(chunk, "size");
|
||||
if valid || reusable(chunk, &map).is_some() { 0 } else { num(chunk, "compressedSize") }
|
||||
}).sum();
|
||||
let patch = array(&plan, "patches").iter().find(|p| text(p, "path_target").replace('\\', "/") == text(file, "path") &&
|
||||
array(p, "chunks").iter().map(|c| num(c, "compressedSize")).sum::<u64>() < missing_bytes);
|
||||
let delta_ok = if let Some(patch) = patch {
|
||||
match apply_delta(&root, file, patch, &plan, &stage, &mut transfer) {
|
||||
Ok(()) => true,
|
||||
Err(e) => { if cancel.load(Ordering::Relaxed) || http_status_in(&e).map(is_link_expiry_status).unwrap_or(false) { return Err(e); } events.on_log(&format!("gog: delta fallback file={} reason={e}", text(file, "path"))); false }
|
||||
}
|
||||
} else { false };
|
||||
if !delta_ok {
|
||||
let chunks = array(file, "chunks");
|
||||
if chunks.is_empty() && num(file, "size") > 0 {
|
||||
let offset = num(file, "offset");
|
||||
let remote = text(file, "remotePath");
|
||||
let endpoints = if remote.starts_with("https://") { vec![remote.to_string()] } else { urls(&plan["links"], text(file, "product"), remote.trim_start_matches('/')) };
|
||||
transfer.fetch(&endpoints, Some((offset, offset + num(file, "size") - 1)), &stage, num(file, "size"))?;
|
||||
} else {
|
||||
let mut output = OpenOptions::new().create(true).truncate(false).read(true).write(true).open(&stage).map_err(|e| e.to_string())?;
|
||||
let mut offset = 0u64;
|
||||
for chunk in chunks {
|
||||
if cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
output.seek(SeekFrom::Start(offset)).map_err(|e| e.to_string())?;
|
||||
let valid_stage = hash_range(&mut output, num(chunk, "size")).map(|h| h.eq_ignore_ascii_case(text(chunk, "md5"))).unwrap_or(false);
|
||||
output.seek(SeekFrom::Start(offset)).map_err(|e| e.to_string())?;
|
||||
if valid_stage { reused += num(chunk, "size"); }
|
||||
else if let Some(old) = reusable(chunk, &map) {
|
||||
let mut source = File::open(old.path).map_err(|e| e.to_string())?;
|
||||
source.seek(SeekFrom::Start(old.offset)).map_err(|e| e.to_string())?;
|
||||
std::io::copy(&mut source.take(old.size), &mut output).map_err(|e| e.to_string())?;
|
||||
reused += old.size;
|
||||
} else {
|
||||
download_chunk(&mut transfer, &plan["links"], text(file, "product"), chunk, &stage.with_extension("packed"), &mut output)?;
|
||||
}
|
||||
offset += num(chunk, "size");
|
||||
}
|
||||
output.set_len(num(file, "size")).map_err(|e| e.to_string())?;
|
||||
output.sync_all().map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let unhashed_range = array(file, "chunks").is_empty() && !valid_md5(text(file, "md5")) && text(file, "sha256").is_empty();
|
||||
if !matches(&stage, file) && !(unhashed_range && fs::metadata(&stage).map(|m| m.len() == num(file, "size")).unwrap_or(false)) { return Err(format!("GOG target verification failed: {}", text(file, "path"))); }
|
||||
if cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
inside(&root, text(file, "path"))?;
|
||||
fs::create_dir_all(path.parent().ok_or("GOG file has no parent")?).map_err(|e| e.to_string())?;
|
||||
File::open(&stage).and_then(|f| f.sync_all()).map_err(|e| e.to_string())?;
|
||||
fs::rename(&stage, &path).map_err(|e| e.to_string())?;
|
||||
applied += num(file, "size"); done += 1;
|
||||
events.on_file_done(text(file, "path"), num(file, "size"), false, done, files.len() as u32, transfer.wire, transfer.total);
|
||||
events.on_maintenance(transfer.wire, reused, applied);
|
||||
events.on_log(&format!("gog: maintenance wire={} reused={reused} applied={applied} files={done}", transfer.wire));
|
||||
}
|
||||
for old in array(&plan, "oldFiles") {
|
||||
if cancel.load(Ordering::Relaxed) { return Err("cancelled".into()); }
|
||||
if !seen.contains(&text(old, "path").to_lowercase()) {
|
||||
let path = inside(&root, text(old, "path"))?;
|
||||
if matches(&path, old) { fs::remove_file(path).map_err(|e| e.to_string())?; }
|
||||
}
|
||||
}
|
||||
events.on_log(&format!("gog: maintenance complete wire={} reused={reused} applied={applied}", transfer.wire));
|
||||
Ok((transfer.wire, done))
|
||||
};
|
||||
match work() {
|
||||
Ok((bytes, files)) => { result.success = true; result.bytes_written = bytes; result.files_done = files; }
|
||||
Err(error) => { result.cancelled = cancel.load(Ordering::Relaxed); result.link_expiry = http_status_in(&error).map(is_link_expiry_status).unwrap_or(false); result.error = error; }
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use flate2::{write::ZlibEncoder, Compression};
|
||||
use serde_json::json;
|
||||
use std::net::TcpListener;
|
||||
use std::sync::{Arc, atomic::AtomicU64};
|
||||
|
||||
struct Events;
|
||||
impl GogEvents for Events {
|
||||
fn on_file_done(&self, _: &str, _: u64, _: bool, _: u32, _: u32, _: u64, _: u64) {}
|
||||
fn on_log(&self, _: &str) {}
|
||||
}
|
||||
struct Temp(PathBuf);
|
||||
impl Temp {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!("gog-maintenance-{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
|
||||
fs::create_dir_all(&path).unwrap(); Self(path)
|
||||
}
|
||||
}
|
||||
impl Drop for Temp { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } }
|
||||
|
||||
struct Server { base: String, bytes: Arc<AtomicU64>, stop: Arc<AtomicBool>, thread: Option<std::thread::JoinHandle<()>> }
|
||||
impl Server {
|
||||
fn new(payloads: HashMap<String, Vec<u8>>, range: bool) -> Self {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let stop = Arc::new(AtomicBool::new(false)); let bytes = Arc::new(AtomicU64::new(0));
|
||||
let (stopped, count) = (stop.clone(), bytes.clone());
|
||||
let thread = std::thread::spawn(move || {
|
||||
while !stopped.load(Ordering::Relaxed) {
|
||||
if let Ok((mut stream, _)) = listener.accept() {
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap();
|
||||
let mut request = Vec::new(); let mut one = [0u8];
|
||||
while stream.read(&mut one).unwrap_or(0) > 0 { request.push(one[0]); if request.ends_with(b"\r\n\r\n") { break; } }
|
||||
let request = String::from_utf8_lossy(&request);
|
||||
let path = request.split_whitespace().nth(1).unwrap_or("");
|
||||
if let Some(body) = payloads.get(path) {
|
||||
let status = if range { "206 Partial Content" } else { "200 OK" };
|
||||
let _ = write!(stream, "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
|
||||
if stream.write_all(body).is_ok() { count.fetch_add(body.len() as u64, Ordering::Relaxed); }
|
||||
} else { let _ = stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); }
|
||||
} else { std::thread::sleep(std::time::Duration::from_millis(2)); }
|
||||
}
|
||||
});
|
||||
Self { base, bytes, stop, thread: Some(thread) }
|
||||
}
|
||||
}
|
||||
impl Drop for Server { fn drop(&mut self) { self.stop.store(true, Ordering::Relaxed); if let Some(thread) = self.thread.take() { thread.join().unwrap(); } } }
|
||||
|
||||
#[test]
|
||||
fn continuing_download_may_exceed_the_read_timeout_in_total() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(3))).unwrap();
|
||||
let mut request = Vec::new(); let mut byte = [0u8];
|
||||
while stream.read(&mut byte).unwrap() > 0 { request.push(byte[0]); if request.ends_with(b"\r\n\r\n") { break; } }
|
||||
stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\n").unwrap();
|
||||
for byte in b"abcd" {
|
||||
stream.write_all(&[*byte]).unwrap(); stream.flush().unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(400));
|
||||
}
|
||||
});
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
let client = http_client(std::time::Duration::from_secs(1)).unwrap();
|
||||
let body = runtime.block_on(async { client.get(url).send().await.unwrap().bytes().await.unwrap() });
|
||||
assert_eq!(&body[..], b"abcd");
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
fn chunk(data: &[u8]) -> (Value, String, Vec<u8>) {
|
||||
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default()); encoder.write_all(data).unwrap();
|
||||
let packed = encoder.finish().unwrap(); let hash = md5_hex(&packed);
|
||||
(json!({"md5": md5_hex(data), "size": data.len(), "compressedMd5": hash, "compressedSize": packed.len()}),
|
||||
format!("/{}", super::super::plan::build_cdn_path(&hash)), packed)
|
||||
}
|
||||
fn execute(root: &Path, files: Value, old: Value, server: &Server) -> GogRunResult {
|
||||
let plan = json!({"files": files, "oldFiles": old, "patches": [], "links": {"1": [server.base]}, "downloadBytes": 4096});
|
||||
run(&GogRequest { install_dir: root.to_string_lossy().into_owned(), depot_manifests: vec![plan.to_string()], ..Default::default() }, &AtomicBool::new(false), &Events)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuses_moved_and_repeated_chunks_and_downloads_only_missing_bytes() {
|
||||
let temp = Temp::new();
|
||||
let (a, _, _) = chunk(b"aaaa"); let (b, path, packed) = chunk(b"bbbb");
|
||||
fs::write(temp.0.join("archive"), b"aaaaaaaa").unwrap();
|
||||
let server = Server::new(HashMap::from([(path, packed.clone())]), false);
|
||||
let old = json!([{"path":"archive", "size":8, "md5":md5_hex(b"aaaaaaaa"), "chunks":[a,a]}]);
|
||||
let files = json!([{"path":"archive", "size":12, "md5":md5_hex(b"bbbbaaaaaaaa"), "chunks":[b,a,a], "product":"1"}]);
|
||||
let result = execute(&temp.0, files, old, &server);
|
||||
assert!(result.success, "{}", result.error);
|
||||
assert_eq!(fs::read(temp.0.join("archive")).unwrap(), b"bbbbaaaaaaaa");
|
||||
assert_eq!(server.bytes.load(Ordering::Relaxed), packed.len() as u64);
|
||||
assert_eq!(result.bytes_written, packed.len() as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revalidates_partial_staging_and_preserves_original_until_verified() {
|
||||
let temp = Temp::new(); let (a, _, _) = chunk(b"aaaa"); let (b, path, packed) = chunk(b"bbbb");
|
||||
let stages = temp.0.join(".droiddeck-gog/stage"); fs::create_dir_all(&stages).unwrap();
|
||||
fs::write(temp.0.join("archive"), b"original").unwrap();
|
||||
fs::write(stages.join(md5_hex(b"archive")), b"aaaabadd").unwrap();
|
||||
let server = Server::new(HashMap::from([(path, packed.clone())]), false);
|
||||
let files = json!([{"path":"archive", "size":8, "md5":md5_hex(b"aaaabbbb"), "chunks":[a,b], "product":"1"}]);
|
||||
let result = execute(&temp.0, files, json!([]), &server);
|
||||
assert!(result.success, "{}", result.error);
|
||||
assert_eq!(server.bytes.load(Ordering::Relaxed), packed.len() as u64);
|
||||
assert_eq!(fs::read(temp.0.join("archive")).unwrap(), b"aaaabbbb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_files_need_no_network_and_obsolete_modified_files_survive() {
|
||||
let temp = Temp::new(); let (a, _, _) = chunk(b"aaaa");
|
||||
fs::write(temp.0.join("current"), b"aaaa").unwrap();
|
||||
fs::write(temp.0.join("obsolete"), b"old").unwrap(); fs::write(temp.0.join("modded"), b"mod").unwrap();
|
||||
let server = Server::new(HashMap::new(), false);
|
||||
let files = json!([{"path":"current", "size":4, "md5":md5_hex(b"aaaa"), "chunks":[a], "product":"1"}, {"path":"empty", "size":0, "chunks":[], "product":"1"}]);
|
||||
let old = json!([{"path":"obsolete", "size":3, "md5":md5_hex(b"old")}, {"path":"modded", "size":3, "md5":md5_hex(b"old")}]);
|
||||
let result = execute(&temp.0, files, old, &server);
|
||||
assert!(result.success, "{}", result.error);
|
||||
assert_eq!(server.bytes.load(Ordering::Relaxed), 0);
|
||||
assert!(!temp.0.join("obsolete").exists()); assert!(temp.0.join("modded").exists());
|
||||
assert_eq!(fs::metadata(temp.0.join("empty")).unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gen1_same_size_corruption_is_replaced_using_hash_and_range() {
|
||||
let temp = Temp::new(); fs::write(temp.0.join("game"), b"bad!").unwrap();
|
||||
let server = Server::new(HashMap::from([("/range".to_string(), b"good".to_vec())]), true);
|
||||
let files = json!([{"path":"game", "size":4, "md5":md5_hex(b"good"), "chunks":[], "product":"1", "remotePath":"range", "offset":10}]);
|
||||
let result = execute(&temp.0, files, json!([]), &server);
|
||||
assert!(result.success, "{}", result.error); assert_eq!(fs::read(temp.0.join("game")).unwrap(), b"good");
|
||||
assert_eq!(server.bytes.load(Ordering::Relaxed), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_chunks_never_replace_original_and_expired_links_are_reported() {
|
||||
let temp = Temp::new(); fs::write(temp.0.join("game"), b"old!").unwrap();
|
||||
let (a, path, mut packed) = chunk(b"new!"); packed[0] ^= 1;
|
||||
let server = Server::new(HashMap::from([(path, packed)]), false);
|
||||
let files = json!([{"path":"game", "size":4, "md5":md5_hex(b"new!"), "chunks":[a], "product":"1"}]);
|
||||
let result = execute(&temp.0, files.clone(), json!([]), &server);
|
||||
assert!(!result.success); assert_eq!(fs::read(temp.0.join("game")).unwrap(), b"old!");
|
||||
let missing = Server::new(HashMap::new(), false);
|
||||
let result = execute(&temp.0, files, json!([]), &missing);
|
||||
assert!(result.link_expiry, "{}", result.error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_traversal_symlinks_and_case_collisions_before_fetching() {
|
||||
let temp = Temp::new(); let outside = Temp::new();
|
||||
std::os::unix::fs::symlink(&outside.0, temp.0.join("linked")).unwrap();
|
||||
for path in ["../escape", "/absolute", "a/./b", "a//b", "linked/game"] { assert!(inside(&temp.0, path).is_err(), "{path}"); }
|
||||
let server = Server::new(HashMap::new(), false);
|
||||
let result = execute(&temp.0, json!([{"path":"Game"}, {"path":"game"}]), json!([]), &server);
|
||||
assert!(!result.success); assert_eq!(server.bytes.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_xdelta_downloads_only_delta_and_corrupt_source_falls_back() {
|
||||
let old = b"the old archive contents\n".repeat(4096);
|
||||
let mut new = b"the new archive contents\n".to_vec(); new.extend_from_slice(&old); new.extend_from_slice(b"END\n");
|
||||
let delta = include_bytes!("fixtures/update.vcdiff");
|
||||
let (patch_chunk, patch_url, packed_delta) = chunk(delta);
|
||||
let (target_chunk, target_url, packed_target) = chunk(&new);
|
||||
for mode in 0..3 {
|
||||
let corrupt = mode == 1;
|
||||
let temp = Temp::new();
|
||||
fs::write(temp.0.join("game"), if corrupt { vec![b'x'; old.len()] } else { old.clone() }).unwrap();
|
||||
let (delta_chunk, delta_url, delta_body) = if mode == 2 { chunk(b"unsupported VCDIFF") } else { (patch_chunk.clone(), patch_url.clone(), packed_delta.clone()) };
|
||||
let server = Server::new(HashMap::from([(delta_url, delta_body.clone()), (target_url.clone(), packed_target.clone())]), false);
|
||||
let plan = json!({"files":[{"path":"game", "product":"1", "size":new.len(), "md5":md5_hex(&new), "chunks":[target_chunk]}],
|
||||
"oldFiles":[{"path":"game", "size":old.len(), "md5":md5_hex(&old), "chunks":[]}],
|
||||
"patches":[{"path_source":"game", "path_target":"game", "product":"1", "md5_source":md5_hex(&old), "md5_target":md5_hex(&new), "md5":if mode == 2 { md5_hex(b"unsupported VCDIFF") } else { md5_hex(delta) }, "chunks":[delta_chunk]}],
|
||||
"links":{"1":[server.base]}, "patchLinks":{"1":[server.base]}, "downloadBytes":packed_target.len()});
|
||||
let result = run(&GogRequest {install_dir:temp.0.to_string_lossy().into_owned(), depot_manifests:vec![plan.to_string()], ..Default::default()}, &AtomicBool::new(false), &Events);
|
||||
assert!(result.success, "{}", result.error);
|
||||
assert_eq!(fs::read(temp.0.join("game")).unwrap(), new);
|
||||
assert_eq!(server.bytes.load(Ordering::Relaxed), match mode { 1 => packed_target.len(), 2 => delta_body.len() + packed_target.len(), _ => packed_delta.len() } as u64);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_chunks_starting_with_x_are_not_mistaken_for_zlib() {
|
||||
let temp = Temp::new(); let raw = b"xyz stored data";
|
||||
let hash = md5_hex(raw);
|
||||
let path = format!("/{}", super::super::plan::build_cdn_path(&hash));
|
||||
let server = Server::new(HashMap::from([(path, raw.to_vec())]), false);
|
||||
let result = execute(&temp.0, json!([{"path":"game", "product":"1", "size":raw.len(), "md5":hash,
|
||||
"chunks":[{"md5":hash,"compressedMd5":hash,"size":raw.len(),"compressedSize":raw.len()}]}]), json!([]), &server);
|
||||
assert!(result.success, "{}", result.error);
|
||||
assert_eq!(fs::read(temp.0.join("game")).unwrap(), raw);
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
@@ -0,0 +1,7 @@
|
||||
Xdelta3 decoder from jmacd/xdelta revision 0525275fe4b553a10f38e455d30c60dc6ed9b45d (release3_0_apl), the
|
||||
Apache-2.0 revision used by heroic-gogdl. Upstream sources are unmodified.
|
||||
https://github.com/jmacd/xdelta/tree/0525275/xdelta3
|
||||
|
||||
DroidDeck's streaming wrapper is src/gog/delta.c. Encoding and secondary
|
||||
compression are disabled, matching heroic-gogdl's decoder baseline. Unsupported
|
||||
streams fall back to verified Galaxy chunks. No Python runtime is required.
|
||||
@@ -0,0 +1,171 @@
|
||||
/* xdelta3 - delta compression tools and library
|
||||
Copyright 2016 Joshua MacDonald
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
/******************************************************************
|
||||
SOFT string matcher
|
||||
******************************************************************/
|
||||
|
||||
#if XD3_BUILD_SOFT
|
||||
|
||||
#define TEMPLATE soft
|
||||
#define LLOOK stream->smatcher.large_look
|
||||
#define LSTEP stream->smatcher.large_step
|
||||
#define SLOOK stream->smatcher.small_look
|
||||
#define SCHAIN stream->smatcher.small_chain
|
||||
#define SLCHAIN stream->smatcher.small_lchain
|
||||
#define MAXLAZY stream->smatcher.max_lazy
|
||||
#define LONGENOUGH stream->smatcher.long_enough
|
||||
|
||||
#define SOFTCFG 1
|
||||
#include "xdelta3.c"
|
||||
#undef SOFTCFG
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
|
||||
#define SOFTCFG 0
|
||||
|
||||
/************************************************************
|
||||
FASTEST string matcher
|
||||
**********************************************************/
|
||||
#if XD3_BUILD_FASTEST
|
||||
#define TEMPLATE fastest
|
||||
#define LLOOK 9
|
||||
#define LSTEP 26
|
||||
#define SLOOK 4U
|
||||
#define SCHAIN 1
|
||||
#define SLCHAIN 1
|
||||
#define MAXLAZY 6
|
||||
#define LONGENOUGH 6
|
||||
|
||||
#include "xdelta3.c"
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
|
||||
/************************************************************
|
||||
FASTER string matcher
|
||||
**********************************************************/
|
||||
#if XD3_BUILD_FASTER
|
||||
#define TEMPLATE faster
|
||||
#define LLOOK 9
|
||||
#define LSTEP 15
|
||||
#define SLOOK 4U
|
||||
#define SCHAIN 1
|
||||
#define SLCHAIN 1
|
||||
#define MAXLAZY 18
|
||||
#define LONGENOUGH 18
|
||||
|
||||
#include "xdelta3.c"
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
|
||||
/******************************************************
|
||||
FAST string matcher
|
||||
********************************************************/
|
||||
#if XD3_BUILD_FAST
|
||||
#define TEMPLATE fast
|
||||
#define LLOOK 9
|
||||
#define LSTEP 8
|
||||
#define SLOOK 4U
|
||||
#define SCHAIN 4
|
||||
#define SLCHAIN 1
|
||||
#define MAXLAZY 18
|
||||
#define LONGENOUGH 35
|
||||
|
||||
#include "xdelta3.c"
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
|
||||
/**************************************************
|
||||
SLOW string matcher
|
||||
**************************************************************/
|
||||
#if XD3_BUILD_SLOW
|
||||
#define TEMPLATE slow
|
||||
#define LLOOK 9
|
||||
#define LSTEP 2
|
||||
#define SLOOK 4U
|
||||
#define SCHAIN 44
|
||||
#define SLCHAIN 13
|
||||
#define MAXLAZY 90
|
||||
#define LONGENOUGH 70
|
||||
|
||||
#include "xdelta3.c"
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
|
||||
/********************************************************
|
||||
DEFAULT string matcher
|
||||
************************************************************/
|
||||
#if XD3_BUILD_DEFAULT
|
||||
#define TEMPLATE default
|
||||
#define LLOOK 9
|
||||
#define LSTEP 3
|
||||
#define SLOOK 4U
|
||||
#define SCHAIN 8
|
||||
#define SLCHAIN 2
|
||||
#define MAXLAZY 36
|
||||
#define LONGENOUGH 70
|
||||
|
||||
#include "xdelta3.c"
|
||||
|
||||
#undef TEMPLATE
|
||||
#undef LLOOK
|
||||
#undef SLOOK
|
||||
#undef LSTEP
|
||||
#undef SCHAIN
|
||||
#undef SLCHAIN
|
||||
#undef MAXLAZY
|
||||
#undef LONGENOUGH
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,167 @@
|
||||
/* xdelta3 - delta compression tools and library
|
||||
Copyright 2016 Joshua MacDonald
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
#ifndef _XDELTA3_HASH_H_
|
||||
#define _XDELTA3_HASH_H_
|
||||
|
||||
#if XD3_DEBUG
|
||||
#define SMALL_HASH_DEBUG1(s,inp) \
|
||||
uint32_t debug_state; \
|
||||
uint32_t debug_hval = xd3_checksum_hash (& (s)->small_hash, \
|
||||
xd3_scksum (&debug_state, (inp), (s)->smatcher.small_look))
|
||||
#define SMALL_HASH_DEBUG2(s,inp) \
|
||||
XD3_ASSERT (debug_hval == xd3_checksum_hash (& (s)->small_hash, \
|
||||
xd3_scksum (&debug_state, (inp), (s)->smatcher.small_look)))
|
||||
#else
|
||||
#define SMALL_HASH_DEBUG1(s,inp)
|
||||
#define SMALL_HASH_DEBUG2(s,inp)
|
||||
#endif /* XD3_DEBUG */
|
||||
|
||||
/* This is a good hash multiplier for 32-bit LCGs: see "linear
|
||||
* congruential generators of different sizes and good lattice
|
||||
* structure" */
|
||||
static const uint32_t hash_multiplier = 1597334677U;
|
||||
|
||||
/***********************************************************************
|
||||
Permute stuff
|
||||
***********************************************************************/
|
||||
|
||||
#if HASH_PERMUTE == 0
|
||||
#define PERMUTE(x) (x)
|
||||
#else
|
||||
#define PERMUTE(x) (__single_hash[(uint32_t)x])
|
||||
|
||||
extern const uint16_t __single_hash[256];
|
||||
#endif
|
||||
|
||||
/* Update the checksum state. */
|
||||
#if ADLER_LARGE_CKSUM
|
||||
inline uint32_t
|
||||
xd3_large_cksum_update (uint32_t cksum,
|
||||
const uint8_t *base,
|
||||
usize_t look) {
|
||||
uint32_t old_c = PERMUTE(base[0]);
|
||||
uint32_t new_c = PERMUTE(base[look]);
|
||||
uint32_t low = ((cksum & 0xffff) - old_c + new_c) & 0xffff;
|
||||
uint32_t high = ((cksum >> 16) - (old_c * look) + low) & 0xffff;
|
||||
return (high << 16) | low;
|
||||
}
|
||||
#else
|
||||
/* TODO: revisit this topic */
|
||||
#endif
|
||||
|
||||
#if UNALIGNED_OK
|
||||
#define UNALIGNED_READ32(dest,src) (*(dest)) = (*(uint32_t*)(src))
|
||||
#else
|
||||
#define UNALIGNED_READ32(dest,src) memcpy((dest), (src), 4);
|
||||
#endif
|
||||
|
||||
/* TODO: small cksum is hard-coded for 4 bytes (i.e., "look" is unused) */
|
||||
static inline uint32_t
|
||||
xd3_scksum (uint32_t *state,
|
||||
const uint8_t *base,
|
||||
const usize_t look)
|
||||
{
|
||||
UNALIGNED_READ32(state, base);
|
||||
return (*state) * hash_multiplier;
|
||||
}
|
||||
static inline uint32_t
|
||||
xd3_small_cksum_update (uint32_t *state,
|
||||
const uint8_t *base,
|
||||
usize_t look)
|
||||
{
|
||||
UNALIGNED_READ32(state, base+1);
|
||||
return (*state) * hash_multiplier;
|
||||
}
|
||||
|
||||
/***********************************************************************
|
||||
Ctable stuff
|
||||
***********************************************************************/
|
||||
|
||||
static inline usize_t
|
||||
xd3_checksum_hash (const xd3_hash_cfg *cfg, const usize_t cksum)
|
||||
{
|
||||
return (cksum >> cfg->shift) ^ (cksum & cfg->mask);
|
||||
}
|
||||
|
||||
/***********************************************************************
|
||||
Cksum function
|
||||
***********************************************************************/
|
||||
|
||||
#if ADLER_LARGE_CKSUM
|
||||
static inline uint32_t
|
||||
xd3_lcksum (const uint8_t *seg, const usize_t ln)
|
||||
{
|
||||
usize_t i = 0;
|
||||
uint32_t low = 0;
|
||||
uint32_t high = 0;
|
||||
|
||||
for (; i < ln; i += 1)
|
||||
{
|
||||
low += PERMUTE(*seg++);
|
||||
high += low;
|
||||
}
|
||||
|
||||
return ((high & 0xffff) << 16) | (low & 0xffff);
|
||||
}
|
||||
#else
|
||||
static inline uint32_t
|
||||
xd3_lcksum (const uint8_t *seg, const usize_t ln)
|
||||
{
|
||||
usize_t i, j;
|
||||
uint32_t h = 0;
|
||||
for (i = 0, j = ln - 1; i < ln; ++i, --j) {
|
||||
h += PERMUTE(seg[i]) * hash_multiplier_powers[j];
|
||||
}
|
||||
return h;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if XD3_ENCODER
|
||||
static usize_t
|
||||
xd3_size_log2 (usize_t slots)
|
||||
{
|
||||
int bits = 28; /* This should not be an unreasonable limit. */
|
||||
int i;
|
||||
|
||||
for (i = 3; i <= bits; i += 1)
|
||||
{
|
||||
if (slots < (1U << i))
|
||||
{
|
||||
/* TODO: this is compaction=1 in checksum_test.cc and maybe should
|
||||
* not be fixed at -1. */
|
||||
bits = i - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return bits;
|
||||
}
|
||||
|
||||
static void
|
||||
xd3_size_hashtable (xd3_stream *stream,
|
||||
usize_t slots,
|
||||
xd3_hash_cfg *cfg)
|
||||
{
|
||||
int bits = xd3_size_log2 (slots);
|
||||
|
||||
/* TODO: there's a 32-bit assumption here */
|
||||
cfg->size = (1 << bits);
|
||||
cfg->mask = (cfg->size - 1);
|
||||
cfg->shift = 32 - bits;
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,370 @@
|
||||
/* xdelta3 - delta compression tools and library
|
||||
Copyright 2016 Joshua MacDonald
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
#ifndef XDELTA3_INTERNAL_H__
|
||||
#define XDELTA3_INTERNAL_H__
|
||||
|
||||
#include "xdelta3.h"
|
||||
|
||||
typedef struct _main_file main_file;
|
||||
typedef struct _main_extcomp main_extcomp;
|
||||
|
||||
void main_buffree (void *ptr);
|
||||
void* main_bufalloc (size_t size);
|
||||
void main_file_init (main_file *xfile);
|
||||
int main_file_close (main_file *xfile);
|
||||
void main_file_cleanup (main_file *xfile);
|
||||
int main_file_isopen (main_file *xfile);
|
||||
int main_file_open (main_file *xfile, const char* name, int mode);
|
||||
int main_file_exists (main_file *xfile);
|
||||
int xd3_whole_append_window (xd3_stream *stream);
|
||||
int xd3_main_cmdline (int argc, char **argv);
|
||||
int main_file_read (main_file *ifile,
|
||||
uint8_t *buf,
|
||||
size_t size,
|
||||
size_t *nread,
|
||||
const char *msg);
|
||||
int main_file_write (main_file *ofile, uint8_t *buf,
|
||||
usize_t size, const char *msg);
|
||||
int test_compare_files (const char* f0, const char* f1);
|
||||
usize_t xd3_bytes_on_srcblk (xd3_source *src, xoff_t blkno);
|
||||
xoff_t xd3_source_eof(const xd3_source *src);
|
||||
uint32_t xd3_large_cksum_update (uint32_t cksum,
|
||||
const uint8_t *base,
|
||||
usize_t look);
|
||||
int xd3_emit_byte (xd3_stream *stream,
|
||||
xd3_output **outputp,
|
||||
uint8_t code);
|
||||
|
||||
int xd3_emit_bytes (xd3_stream *stream,
|
||||
xd3_output **outputp,
|
||||
const uint8_t *base,
|
||||
usize_t size);
|
||||
xd3_output* xd3_alloc_output (xd3_stream *stream,
|
||||
xd3_output *old_output);
|
||||
|
||||
int xd3_encode_init_full (xd3_stream *stream);
|
||||
size_t xd3_pow2_roundup (size_t x);
|
||||
int xd3_process_stream (int is_encode,
|
||||
xd3_stream *stream,
|
||||
int (*func) (xd3_stream *),
|
||||
int close_stream,
|
||||
const uint8_t *input,
|
||||
usize_t input_size,
|
||||
uint8_t *output,
|
||||
usize_t *output_size,
|
||||
usize_t output_size_max);
|
||||
|
||||
#if PYTHON_MODULE || SWIG_MODULE || NOT_MAIN
|
||||
int xd3_main_cmdline (int argc, char **argv);
|
||||
#endif
|
||||
|
||||
/* main_file->mode values */
|
||||
typedef enum
|
||||
{
|
||||
XO_READ = 0,
|
||||
XO_WRITE = 1
|
||||
} main_file_modes;
|
||||
|
||||
#ifndef XD3_POSIX
|
||||
#define XD3_POSIX 0
|
||||
#endif
|
||||
#ifndef XD3_STDIO
|
||||
#define XD3_STDIO 0
|
||||
#endif
|
||||
#ifndef XD3_WIN32
|
||||
#define XD3_WIN32 0
|
||||
#endif
|
||||
#ifndef NOT_MAIN
|
||||
#define NOT_MAIN 0
|
||||
#endif
|
||||
|
||||
/* If none are set, default to posix. */
|
||||
#if (XD3_POSIX + XD3_STDIO + XD3_WIN32) == 0
|
||||
#undef XD3_POSIX
|
||||
#define XD3_POSIX 1
|
||||
#endif
|
||||
|
||||
struct _main_file
|
||||
{
|
||||
#if XD3_WIN32
|
||||
HANDLE file;
|
||||
#elif XD3_STDIO
|
||||
FILE *file;
|
||||
#elif XD3_POSIX
|
||||
int file;
|
||||
#endif
|
||||
|
||||
int mode; /* XO_READ and XO_WRITE */
|
||||
const char *filename; /* File name or /dev/stdin,
|
||||
* /dev/stdout, /dev/stderr. */
|
||||
char *filename_copy; /* File name or /dev/stdin,
|
||||
* /dev/stdout, /dev/stderr. */
|
||||
const char *realname; /* File name or /dev/stdin,
|
||||
* /dev/stdout, /dev/stderr. */
|
||||
const main_extcomp *compressor; /* External compression struct. */
|
||||
int flags; /* RD_FIRST, RD_NONEXTERNAL, ... */
|
||||
xoff_t nread; /* for input position */
|
||||
xoff_t nwrite; /* for output position */
|
||||
uint8_t *snprintf_buf; /* internal snprintf() use */
|
||||
int size_known; /* Set by main_set_souze */
|
||||
xoff_t source_position; /* for avoiding seek in getblk_func */
|
||||
int seek_failed; /* after seek fails once, try FIFO */
|
||||
};
|
||||
|
||||
#ifdef _WIN32
|
||||
#define vsnprintf_func _vsnprintf
|
||||
#define snprintf_func _snprintf
|
||||
#else
|
||||
#define vsnprintf_func vsnprintf
|
||||
#define snprintf_func snprintf
|
||||
#endif
|
||||
#define short_sprintf(sb,fmt,...) \
|
||||
snprintf_func((sb).buf,sizeof((sb).buf),fmt,__VA_ARGS__)
|
||||
|
||||
/* Type used for short snprintf calls. */
|
||||
typedef struct {
|
||||
char buf[48];
|
||||
} shortbuf;
|
||||
|
||||
/* Prior to SVN 303 this function was only defined in DJGPP and WIN32
|
||||
* environments and other platforms would use the builtin snprintf()
|
||||
* with an arrangement of macros below. In OS X 10.6, Apply made
|
||||
* snprintf() a macro, which defeated those macros (since snprintf
|
||||
* would be evaluated before its argument macros were expanded,
|
||||
* therefore always define xsnprintf_func. */
|
||||
#undef PRINTF_ATTRIBUTE
|
||||
#ifdef __GNUC__
|
||||
/* Let's just assume no one uses gcc 2.x! */
|
||||
#define PRINTF_ATTRIBUTE(x,y) __attribute__ ((__format__ (__printf__, x, y)))
|
||||
#else
|
||||
#define PRINTF_ATTRIBUTE(x,y)
|
||||
#endif
|
||||
|
||||
/* Underlying xprintf() */
|
||||
int xsnprintf_func (char *str, int n, const char *fmt, ...)
|
||||
PRINTF_ATTRIBUTE(3,4);
|
||||
|
||||
/* XPR(NT "", ...) (used by main) prefixes an "xdelta3: " to the output. */
|
||||
void xprintf(const char *fmt, ...) PRINTF_ATTRIBUTE(1,2);
|
||||
#define XPR xprintf
|
||||
#define NT "xdelta3: "
|
||||
#define NTR ""
|
||||
|
||||
#ifndef UINT32_MAX
|
||||
#define UINT32_MAX 4294967295U
|
||||
#endif
|
||||
|
||||
#ifndef UINT64_MAX
|
||||
#define UINT64_MAX 18446744073709551615ULL
|
||||
#endif
|
||||
|
||||
#define UINT32_OFLOW_MASK 0xfe000000U
|
||||
#define UINT64_OFLOW_MASK 0xfe00000000000000ULL
|
||||
|
||||
/*********************************************************************
|
||||
Integer encoder/decoder functions
|
||||
**********************************************************************/
|
||||
|
||||
/* Consume N bytes of input, only used by the decoder. */
|
||||
#define DECODE_INPUT(n) \
|
||||
do { \
|
||||
stream->total_in += (xoff_t) (n); \
|
||||
stream->avail_in -= (n); \
|
||||
stream->next_in += (n); \
|
||||
} while (0)
|
||||
|
||||
#define DECODE_INTEGER_TYPE(PART,OFLOW) \
|
||||
while (stream->avail_in != 0) \
|
||||
{ \
|
||||
usize_t next = stream->next_in[0]; \
|
||||
\
|
||||
DECODE_INPUT(1); \
|
||||
\
|
||||
if (PART & OFLOW) \
|
||||
{ \
|
||||
stream->msg = "overflow in decode_integer"; \
|
||||
return XD3_INVALID_INPUT; \
|
||||
} \
|
||||
\
|
||||
PART = (PART << 7) | (next & 127); \
|
||||
\
|
||||
if ((next & 128) == 0) \
|
||||
{ \
|
||||
(*val) = PART; \
|
||||
PART = 0; \
|
||||
return 0; \
|
||||
} \
|
||||
} \
|
||||
\
|
||||
stream->msg = "further input required"; \
|
||||
return XD3_INPUT
|
||||
|
||||
#define READ_INTEGER_TYPE(TYPE, OFLOW) \
|
||||
TYPE val = 0; \
|
||||
const uint8_t *inp = (*inpp); \
|
||||
usize_t next; \
|
||||
\
|
||||
do \
|
||||
{ \
|
||||
if (inp == maxp) \
|
||||
{ \
|
||||
stream->msg = "end-of-input in read_integer"; \
|
||||
return XD3_INVALID_INPUT; \
|
||||
} \
|
||||
\
|
||||
if (val & OFLOW) \
|
||||
{ \
|
||||
stream->msg = "overflow in read_intger"; \
|
||||
return XD3_INVALID_INPUT; \
|
||||
} \
|
||||
\
|
||||
next = (*inp++); \
|
||||
val = (val << 7) | (next & 127); \
|
||||
} \
|
||||
while (next & 128); \
|
||||
\
|
||||
(*valp) = val; \
|
||||
(*inpp) = inp; \
|
||||
\
|
||||
return 0
|
||||
|
||||
#define EMIT_INTEGER_TYPE() \
|
||||
/* max 64-bit value in base-7 encoding is 9.1 bytes */ \
|
||||
uint8_t buf[10]; \
|
||||
usize_t bufi = 10; \
|
||||
\
|
||||
/* This loop performs division and turns on all MSBs. */ \
|
||||
do \
|
||||
{ \
|
||||
buf[--bufi] = (num & 127) | 128; \
|
||||
num >>= 7U; \
|
||||
} \
|
||||
while (num != 0); \
|
||||
\
|
||||
/* Turn off MSB of the last byte. */ \
|
||||
buf[9] &= 127; \
|
||||
\
|
||||
return xd3_emit_bytes (stream, output, buf + bufi, 10 - bufi)
|
||||
|
||||
#define IF_SIZEOF32(x) if (num < (1U << (7 * (x)))) return (x);
|
||||
#define IF_SIZEOF64(x) if (num < (1ULL << (7 * (x)))) return (x);
|
||||
|
||||
#if USE_UINT32
|
||||
static inline uint32_t
|
||||
xd3_sizeof_uint32_t (uint32_t num)
|
||||
{
|
||||
IF_SIZEOF32(1);
|
||||
IF_SIZEOF32(2);
|
||||
IF_SIZEOF32(3);
|
||||
IF_SIZEOF32(4);
|
||||
return 5;
|
||||
}
|
||||
|
||||
static inline int
|
||||
xd3_decode_uint32_t (xd3_stream *stream, uint32_t *val)
|
||||
{ DECODE_INTEGER_TYPE (stream->dec_32part, UINT32_OFLOW_MASK); }
|
||||
|
||||
static inline int
|
||||
xd3_read_uint32_t (xd3_stream *stream, const uint8_t **inpp,
|
||||
const uint8_t *maxp, uint32_t *valp)
|
||||
{ READ_INTEGER_TYPE (uint32_t, UINT32_OFLOW_MASK); }
|
||||
|
||||
#if XD3_ENCODER
|
||||
static inline int
|
||||
xd3_emit_uint32_t (xd3_stream *stream, xd3_output **output, uint32_t num)
|
||||
{ EMIT_INTEGER_TYPE (); }
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if USE_UINT64
|
||||
static inline int
|
||||
xd3_decode_uint64_t (xd3_stream *stream, uint64_t *val)
|
||||
{ DECODE_INTEGER_TYPE (stream->dec_64part, UINT64_OFLOW_MASK); }
|
||||
|
||||
#if XD3_ENCODER
|
||||
static inline int
|
||||
xd3_emit_uint64_t (xd3_stream *stream, xd3_output **output, uint64_t num)
|
||||
{ EMIT_INTEGER_TYPE (); }
|
||||
#endif
|
||||
|
||||
/* These are tested but not used */
|
||||
#if REGRESSION_TEST
|
||||
static int
|
||||
xd3_read_uint64_t (xd3_stream *stream, const uint8_t **inpp,
|
||||
const uint8_t *maxp, uint64_t *valp)
|
||||
{ READ_INTEGER_TYPE (uint64_t, UINT64_OFLOW_MASK); }
|
||||
|
||||
static uint32_t
|
||||
xd3_sizeof_uint64_t (uint64_t num)
|
||||
{
|
||||
IF_SIZEOF64(1);
|
||||
IF_SIZEOF64(2);
|
||||
IF_SIZEOF64(3);
|
||||
IF_SIZEOF64(4);
|
||||
IF_SIZEOF64(5);
|
||||
IF_SIZEOF64(6);
|
||||
IF_SIZEOF64(7);
|
||||
IF_SIZEOF64(8);
|
||||
IF_SIZEOF64(9);
|
||||
|
||||
return 10;
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#if SIZEOF_USIZE_T == 4
|
||||
#define USIZE_T_MAX UINT32_MAX
|
||||
#define USIZE_T_MAXBLKSZ 0x80000000U
|
||||
#define xd3_decode_size xd3_decode_uint32_t
|
||||
#define xd3_emit_size xd3_emit_uint32_t
|
||||
#define xd3_sizeof_size xd3_sizeof_uint32_t
|
||||
#define xd3_read_size xd3_read_uint32_t
|
||||
#elif SIZEOF_USIZE_T == 8
|
||||
#define USIZE_T_MAX UINT64_MAX
|
||||
#define USIZE_T_MAXBLKSZ 0x8000000000000000ULL
|
||||
#define xd3_decode_size xd3_decode_uint64_t
|
||||
#define xd3_emit_size xd3_emit_uint64_t
|
||||
#define xd3_sizeof_size xd3_sizeof_uint64_t
|
||||
#define xd3_read_size xd3_read_uint64_t
|
||||
#endif
|
||||
|
||||
#if SIZEOF_XOFF_T == 4
|
||||
#define XOFF_T_MAX UINT32_MAX
|
||||
#define xd3_emit_offset xd3_emit_uint32_t
|
||||
static inline int
|
||||
xd3_decode_offset (xd3_stream *stream, xoff_t *val)
|
||||
{
|
||||
return xd3_decode_uint32_t (stream, (uint32_t*) val);
|
||||
}
|
||||
#elif SIZEOF_XOFF_T == 8
|
||||
#define XOFF_T_MAX UINT64_MAX
|
||||
#define xd3_emit_offset xd3_emit_uint64_t
|
||||
static inline int
|
||||
xd3_decode_offset (xd3_stream *stream, xoff_t *val)
|
||||
{
|
||||
return xd3_decode_uint64_t (stream, (uint64_t*) val);
|
||||
}
|
||||
#endif
|
||||
|
||||
#define USIZE_T_OVERFLOW(a,b) ((USIZE_T_MAX - (usize_t) (a)) < (usize_t) (b))
|
||||
#define XOFF_T_OVERFLOW(a,b) ((XOFF_T_MAX - (xoff_t) (a)) < (xoff_t) (b))
|
||||
|
||||
#define MAX_LRU_SIZE 32U
|
||||
#define XD3_MINSRCWINSZ (XD3_ALLOCSIZE * MAX_LRU_SIZE)
|
||||
#define XD3_MAXSRCWINSZ (1ULL << 31)
|
||||
|
||||
#endif // XDELTA3_INTERNAL_H__
|
||||
@@ -0,0 +1,127 @@
|
||||
/* xdelta3 - delta compression tools and library
|
||||
Copyright 2016 Joshua MacDonald
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
#ifndef __XDELTA3_LIST__
|
||||
#define __XDELTA3_LIST__
|
||||
|
||||
#define XD3_MAKELIST(LTYPE,ETYPE,LNAME) \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _entry (LTYPE* l) \
|
||||
{ \
|
||||
return (ETYPE*) ((char*) l - (ptrdiff_t) &((ETYPE*) 0)->LNAME); \
|
||||
} \
|
||||
\
|
||||
static inline void \
|
||||
LTYPE ## _init (LTYPE *l) \
|
||||
{ \
|
||||
l->next = l; \
|
||||
l->prev = l; \
|
||||
} \
|
||||
\
|
||||
static inline void \
|
||||
LTYPE ## _add (LTYPE *prev, LTYPE *next, LTYPE *ins) \
|
||||
{ \
|
||||
next->prev = ins; \
|
||||
prev->next = ins; \
|
||||
ins->next = next; \
|
||||
ins->prev = prev; \
|
||||
} \
|
||||
\
|
||||
static inline void \
|
||||
LTYPE ## _push_back (LTYPE *l, ETYPE *i) \
|
||||
{ \
|
||||
LTYPE ## _add (l->prev, l, & i->LNAME); \
|
||||
} \
|
||||
\
|
||||
static inline void \
|
||||
LTYPE ## _del (LTYPE *next, \
|
||||
LTYPE *prev) \
|
||||
{ \
|
||||
next->prev = prev; \
|
||||
prev->next = next; \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _remove (ETYPE *f) \
|
||||
{ \
|
||||
LTYPE *i = f->LNAME.next; \
|
||||
LTYPE ## _del (f->LNAME.next, f->LNAME.prev); \
|
||||
return LTYPE ## _entry (i); \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _pop_back (LTYPE *l) \
|
||||
{ \
|
||||
LTYPE *i = l->prev; \
|
||||
LTYPE ## _del (i->next, i->prev); \
|
||||
return LTYPE ## _entry (i); \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _pop_front (LTYPE *l) \
|
||||
{ \
|
||||
LTYPE *i = l->next; \
|
||||
LTYPE ## _del (i->next, i->prev); \
|
||||
return LTYPE ## _entry (i); \
|
||||
} \
|
||||
\
|
||||
static inline int \
|
||||
LTYPE ## _empty (LTYPE *l) \
|
||||
{ \
|
||||
return l == l->next; \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _front (LTYPE *f) \
|
||||
{ \
|
||||
return LTYPE ## _entry (f->next); \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _back (LTYPE *f) \
|
||||
{ \
|
||||
return LTYPE ## _entry (f->prev); \
|
||||
} \
|
||||
\
|
||||
static inline int \
|
||||
LTYPE ## _end (LTYPE *f, ETYPE *i) \
|
||||
{ \
|
||||
return f == & i->LNAME; \
|
||||
} \
|
||||
\
|
||||
static inline ETYPE* \
|
||||
LTYPE ## _next (ETYPE *f) \
|
||||
{ \
|
||||
return LTYPE ## _entry (f->LNAME.next); \
|
||||
} \
|
||||
\
|
||||
static inline usize_t \
|
||||
LTYPE ## _length (LTYPE *l) \
|
||||
{ \
|
||||
LTYPE *p; \
|
||||
int c = 0; \
|
||||
\
|
||||
for (p = l->next; p != l; p = p->next) \
|
||||
{ \
|
||||
c += 1; \
|
||||
} \
|
||||
\
|
||||
return c; \
|
||||
} \
|
||||
\
|
||||
typedef int unused_ ## LTYPE
|
||||
|
||||
#endif
|
||||
+4835
File diff suppressed because it is too large.
Load diff
+1396
File diff suppressed because it is too large.
Load diff
@@ -18,8 +18,9 @@ class SessionBackgroundPrefsTest {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
|
||||
@Test fun nativeIsOptInAndDoesNotChangeDesktopOrExistingPolicies() {
|
||||
assertEquals(SessionPrefs.SUSPEND_MANUAL, SessionPrefs.suspendPolicy(context, "steam"))
|
||||
@Test fun nativeIsTheSteamDefaultWithoutChangingOtherModesOrSavedPolicies() {
|
||||
assertEquals(SessionPrefs.SUSPEND_NATIVE, SessionPrefs.suspendPolicy(context, "steam"))
|
||||
assertEquals(SessionPrefs.SUSPEND_MANUAL, SessionPrefs.suspendPolicy(context, SessionService.MODE_RUN))
|
||||
for (policy in listOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_MANUAL, SessionPrefs.SUSPEND_NEVER,
|
||||
SessionPrefs.SUSPEND_NATIVE)) {
|
||||
SessionPrefs.setSuspendPolicy(context, "steam", policy)
|
||||
@@ -28,6 +29,14 @@ class SessionBackgroundPrefsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun automaticPipDefaultsOnAndHonorsSavedChoices() {
|
||||
assertEquals(true, SessionPrefs.pipAutoEnter(context))
|
||||
SessionPrefs.setPipAutoEnter(context, false)
|
||||
assertEquals(false, SessionPrefs.pipAutoEnter(context))
|
||||
SessionPrefs.setPipAutoEnter(context, true)
|
||||
assertEquals(true, SessionPrefs.pipAutoEnter(context))
|
||||
}
|
||||
|
||||
@Test fun directGamesUseAutoWithoutOverwritingSteamsNativeChoice() {
|
||||
SessionPrefs.setSuspendPolicy(context, SessionService.MODE_STEAM, SessionPrefs.SUSPEND_NATIVE)
|
||||
assertEquals(SessionPrefs.SUSPEND_AUTO, SessionPrefs.suspendPolicy(context, SessionService.MODE_RUN))
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SteamSessionUrlTest {
|
||||
@Test
|
||||
fun onlySupportedSteamNavigationRoutesAreAccepted() {
|
||||
listOf("steam://open/downloads", "steam://uninstall/12345", "steam://uninstall/4294967295")
|
||||
.forEach { assertTrue(it, SteamSessionUrl.isSupported(it)) }
|
||||
listOf("steam://open/settings", "steam://nav/library", "steam://uninstall/0", "steam://uninstall/01",
|
||||
"steam://uninstall/4294967296", "steam://open/downloads\n--exec", "https://example.com")
|
||||
.forEach { assertFalse(it, SteamSessionUrl.isSupported(it)) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bridgeMustConfirmLaunch() {
|
||||
assertTrue(SteamSessionUrl.wasOpened(ok = true, launched = true))
|
||||
assertFalse(SteamSessionUrl.wasOpened(ok = false, launched = true))
|
||||
assertFalse(SteamSessionUrl.wasOpened(ok = true, launched = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resumeTargetsOnlyTheSameLiveSessionAndActivity() {
|
||||
assertTrue(SteamSessionUrl.canResume("session-a", "session-a", running = true, stopping = false, activityDestroyed = false))
|
||||
assertFalse(SteamSessionUrl.canResume("session-a", "session-b", running = true, stopping = false, activityDestroyed = false))
|
||||
assertFalse(SteamSessionUrl.canResume("session-a", "session-a", running = false, stopping = false, activityDestroyed = false))
|
||||
assertFalse(SteamSessionUrl.canResume("session-a", "session-a", running = true, stopping = true, activityDestroyed = false))
|
||||
assertFalse(SteamSessionUrl.canResume("session-a", "session-a", running = true, stopping = false, activityDestroyed = true))
|
||||
assertFalse(SteamSessionUrl.canResume(null, null, running = true, stopping = false, activityDestroyed = false))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import android.app.Application
|
||||
import android.os.Looper
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.junit.Assert.*
|
||||
@@ -9,7 +10,11 @@ import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], application = Application::class)
|
||||
@@ -18,9 +23,12 @@ class StoreLaunchTest {
|
||||
|
||||
private fun install(state: String = StoreGameSidecar.STATE_INSTALLED): File {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.installRoot(app), Store.XBOX), "Deep Rock Galactic")
|
||||
val storeDir = StoreInstallRoot.storeDir(StoreInstallRoot.installRoot(app), Store.XBOX)
|
||||
storeDir.listFiles()?.filter { StoreGameSidecar.read(it)?.id == "9NHFVWX1V7QJ" }?.forEach { it.deleteRecursively() }
|
||||
val folder = File(storeDir, "Deep Rock Galactic")
|
||||
File(folder, "FSD/Binaries/WinGDK/FSD.exe").apply { parentFile!!.mkdirs(); writeText("licensed image") }
|
||||
StoreGameSidecar(Store.XBOX, "9NHFVWX1V7QJ", "Deep Rock Galactic", "FSD/Binaries/WinGDK/FSD.exe", state = state).write(folder)
|
||||
SessionPrefs.setAddedGameRemoved(app, folder.path, false)
|
||||
return folder
|
||||
}
|
||||
|
||||
@@ -53,4 +61,71 @@ class StoreLaunchTest {
|
||||
File(folder, "FSD/Binaries/WinGDK/FSD.exe").delete()
|
||||
assertNull(StoreLaunch.installedGame(app, Store.XBOX, "9NHFVWX1V7QJ"))
|
||||
}
|
||||
|
||||
@Test fun maintenanceBlockedLaunchReportsTheBlockWithoutLaunching() {
|
||||
val folder = install()
|
||||
val operation = com.droiddeck.launcher.stores.maintenance.StoreMaintenance.operationFile(folder)
|
||||
operation.parentFile!!.mkdirs()
|
||||
operation.writeText(JSONObject().put("schema", 1).put("folder", folder.canonicalPath).put("phase", "applying").toString())
|
||||
val blocked = CountDownLatch(1)
|
||||
val ready = AtomicBoolean(false)
|
||||
|
||||
try {
|
||||
StoreLaunch.prepare(app, Store.XBOX, "9NHFVWX1V7QJ", onBlocked = { blocked.countDown() }) {
|
||||
ready.set(true)
|
||||
}
|
||||
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
while (blocked.count > 0 && System.nanoTime() < deadline) {
|
||||
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||
Thread.sleep(10)
|
||||
}
|
||||
assertTrue("the blocked callback was not posted", blocked.await(1, TimeUnit.SECONDS))
|
||||
assertFalse("an excluded install must not reach the launch callback", ready.get())
|
||||
} finally {
|
||||
operation.parentFile?.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun installedTargetWinsOverAnEarlierUpdatingDuplicate() {
|
||||
val updating = install(StoreGameSidecar.STATE_UPDATING)
|
||||
val installed = File(updating.parentFile, "ZZZ installed copy")
|
||||
File(installed, "FSD/Binaries/WinGDK/FSD.exe").apply { parentFile!!.mkdirs(); writeText("installed image") }
|
||||
StoreGameSidecar(Store.XBOX, "9NHFVWX1V7QJ", "Deep Rock Galactic", "FSD/Binaries/WinGDK/FSD.exe").write(installed)
|
||||
|
||||
try {
|
||||
assertEquals(installed, StoreLaunch.findInstalled(app, Store.XBOX, "9NHFVWX1V7QJ")!!.first)
|
||||
} finally {
|
||||
installed.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun prepareScansOffTheCallerAndPostsReadyBackToMainLooper() {
|
||||
val updating = install(StoreGameSidecar.STATE_UPDATING)
|
||||
val installed = File(updating.parentFile, "ZZZ installed copy")
|
||||
File(installed, "FSD/Binaries/WinGDK/FSD.exe").apply { parentFile!!.mkdirs(); writeText("installed image") }
|
||||
StoreGameSidecar(Store.XBOX, "9NHFVWX1V7QJ", "Deep Rock Galactic", "FSD/Binaries/WinGDK/FSD.exe").write(installed)
|
||||
val callbackRan = AtomicBoolean(false)
|
||||
val callbackOnMain = AtomicBoolean(false)
|
||||
val callback = CountDownLatch(1)
|
||||
|
||||
try {
|
||||
StoreLaunch.prepare(app, Store.XBOX, "9NHFVWX1V7QJ") {
|
||||
callbackOnMain.set(Looper.myLooper() == Looper.getMainLooper())
|
||||
callbackRan.set(true)
|
||||
callback.countDown()
|
||||
}
|
||||
|
||||
assertFalse("ready callback must not run inline on the caller", callbackRan.get())
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
while (callback.count > 0 && System.nanoTime() < deadline) {
|
||||
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||
Thread.sleep(10)
|
||||
}
|
||||
assertTrue("ready callback was not posted", callback.await(1, TimeUnit.SECONDS))
|
||||
assertTrue("ready callback must run on the main looper", callbackOnMain.get())
|
||||
} finally {
|
||||
installed.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.droiddeck.launcher.stores.battlenet
|
||||
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.maintenance.MaintenanceAction
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
class BattleNetMaintenanceTest {
|
||||
@Test fun agentManagedGamesOfferOnlyClientHandoffThroughSharedMaintenance() {
|
||||
val folder = File("/tmp/battlenet-agent-game")
|
||||
val game = InstalledStoreGame(StoreGameSidecar(Store.BATTLENET, "wow", "World of Warcraft", ""), folder)
|
||||
|
||||
assertEquals(setOf(MaintenanceAction.OPEN_CLIENT), BattleNetMaintenanceAdapter.capabilities(game))
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
@@ -137,4 +138,40 @@ class DownloadQueueRetryTest {
|
||||
assertTrue(ran.await(5, TimeUnit.SECONDS))
|
||||
awaitFailure(entry.key, "restored")
|
||||
}
|
||||
|
||||
@Test fun maintenanceAdmissionRejectsDuplicateWithoutReplacingSavedQueueItem() {
|
||||
val id = "maintenance-admission-${java.util.UUID.randomUUID()}"
|
||||
val first = CatalogItem(Store.EPIC, id, "First update", imageUrl = null, owned = true)
|
||||
val second = CatalogItem(Store.EPIC, id, "Other operation", imageUrl = null, owned = true)
|
||||
val entry = DownloadEntry(Store.EPIC, id, first.title)
|
||||
val firstFactory = { object : DownloadQueue.DownloadJob {
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? = null
|
||||
override fun cancel(deleteFiles: Boolean) = Unit
|
||||
} }
|
||||
DownloadQueue.holdPaused(entry.key)
|
||||
|
||||
val firstAccepted = DownloadQueue.enqueueIfIdle(app, entry,
|
||||
onAccepted = { SavedQueue.remember(app, first, null) }, factory = firstFactory)
|
||||
val duplicateRemembered = AtomicBoolean(false)
|
||||
val secondAccepted = DownloadQueue.enqueueIfIdle(app, entry.copy(name = second.title),
|
||||
onAccepted = { duplicateRemembered.set(true); SavedQueue.remember(app, second, null) }, factory = firstFactory)
|
||||
|
||||
assertTrue(firstAccepted)
|
||||
assertFalse(secondAccepted)
|
||||
assertFalse(duplicateRemembered.get())
|
||||
assertEquals(DownloadState.PAUSED, DownloadQueue.entry(entry.key)?.state)
|
||||
|
||||
val saved = File(app.filesDir, "store-queue.json")
|
||||
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
var savedFirst = false
|
||||
while (!savedFirst && System.nanoTime() < until) {
|
||||
savedFirst = runCatching {
|
||||
val rows = JSONArray(saved.readText())
|
||||
(0 until rows.length()).any { i -> rows.getJSONObject(i).getJSONObject("item").getString("title") == first.title }
|
||||
}.getOrDefault(false)
|
||||
if (!savedFirst) Thread.sleep(10)
|
||||
}
|
||||
assertTrue("only the accepted operation's saved item should persist", savedFirst)
|
||||
DownloadQueue.clear(app, entry.key)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class GogMaintenanceTest {
|
||||
@get:Rule val temporary = TemporaryFolder()
|
||||
|
||||
@Test fun selectsPublicBranchAndTreatsBuildIdsAsOpaque() {
|
||||
val builds = JSONObject("""{"items":[
|
||||
{"os":"windows","branch":"beta","build_id":"99","generation":2,"link":"https://example.invalid/beta"},
|
||||
{"os":"windows","branch":null,"build_id":"0002","generation":2,"version_name":"RC-final","link":"https://example.invalid/current"},
|
||||
{"os":"windows","branch":null,"build_id":"10","generation":2,"link":"https://example.invalid/old"}]}""")
|
||||
assertEquals("0002", GogBuild.select(builds)!!.id)
|
||||
assertEquals("99", GogBuild.select(builds, branch = "beta")!!.id)
|
||||
assertEquals("10", GogBuild.select(builds, pinned = "10")!!.id)
|
||||
assertNull(GogBuild.select(builds, pinned = "missing"))
|
||||
assertNull(GogBuild.select(builds, branch = "private"))
|
||||
}
|
||||
|
||||
@Test fun migrationRetainsKnownBuildLanguageAndInstalledProducts() {
|
||||
val folder = temporary.newFolder()
|
||||
File(folder, "_gog_manifest.json").writeText("""{"gameId":"1","buildId":"000123"}""")
|
||||
File(folder, "goggame-2.info").writeText("{}")
|
||||
val sidecar = StoreGameSidecar(Store.GOG, "1", "Game", "game.exe", installVersion = "000123",
|
||||
args = listOf("--custom"), env = mapOf("DD_TEST" to "1"), cloud = false, achievements = false,
|
||||
extra = mapOf(StoreLanguage.EXTRA to "pl-PL"))
|
||||
val record = GogInstallRecord.migrate(folder, sidecar)
|
||||
assertEquals("000123", record.build)
|
||||
assertEquals("pl-PL", record.language)
|
||||
assertEquals(listOf("1", "2"), record.products)
|
||||
assertEquals(record.json().toString(), GogInstallRecord.read(folder)!!.json().toString())
|
||||
assertEquals(listOf("--custom"), sidecar.args)
|
||||
assertFalse(sidecar.cloud)
|
||||
}
|
||||
|
||||
@Test fun missingManifestNeverInventsLatestBuild() {
|
||||
val folder = temporary.newFolder()
|
||||
val record = GogInstallRecord.migrate(folder, StoreGameSidecar(Store.GOG, "1", "Game", "game.exe"))
|
||||
assertEquals("offline", record.source)
|
||||
assertEquals("", record.build)
|
||||
assertEquals(0, record.files.length())
|
||||
}
|
||||
|
||||
@Test fun offlineRefreshWithDlcRequiresAnAuthenticMatchingDepotBuild() {
|
||||
val extracted = temporary.newFolder()
|
||||
val app = File(extracted, "app").apply { mkdirs() }
|
||||
val target = GogInstallRecord("1", "depot", build = "0000123", products = listOf("1", "2"))
|
||||
assertThrows(IllegalArgumentException::class.java) { GogOffline.validateDepotInstaller(extracted, target) }
|
||||
File(app, "goggame-1.info").writeText("""{"buildId":"0000999"}""")
|
||||
assertThrows(IllegalArgumentException::class.java) { GogOffline.validateDepotInstaller(extracted, target) }
|
||||
File(app, "goggame-1.info").writeText("""{"buildId":"0000123"}""")
|
||||
GogOffline.validateDepotInstaller(extracted, target)
|
||||
File(app, "goggame-1.info").delete()
|
||||
GogOffline.validateDepotInstaller(extracted, target.copy(source = "offline", build = ""))
|
||||
}
|
||||
|
||||
@Test fun offlineRefreshRetainsTheExistingExecutableLayout() {
|
||||
val installed = temporary.newFolder()
|
||||
val extracted = temporary.newFolder()
|
||||
val app = File(extracted, "app").apply { mkdirs() }
|
||||
File(app, "game.exe").writeText("replacement")
|
||||
File(installed, "goggame-1.info").writeText("{}")
|
||||
assertEquals(extracted, GogOffline.layout(extracted, installed, "1", "game.exe").source)
|
||||
assertEquals("", GogOffline.layout(extracted, installed, "1", "game.exe").prefix)
|
||||
File(installed, "goggame-1.info").delete()
|
||||
assertEquals(extracted, GogOffline.layout(extracted, installed, "1", "app/game.exe").source)
|
||||
val flat = temporary.newFolder()
|
||||
val legacy = GogOffline.layout(flat, installed, "1", "app/game.exe")
|
||||
assertEquals(flat, legacy.source)
|
||||
assertEquals("app/", legacy.prefix)
|
||||
}
|
||||
|
||||
@Test fun offlineInstallerMatchesRegionalLanguageWithoutChoosingAnotherLanguage() {
|
||||
val downloads = JSONObject("""{"installers":[
|
||||
{"id":"de","os":"windows","language":"de","files":[{"downlink":"https://example.invalid/de"}]},
|
||||
{"id":"en","os":"windows","language":"en","files":[{"downlink":"https://example.invalid/en"}]}]}""")
|
||||
assertEquals("en", GogMaintenance.offlineInstaller(downloads, "en-US").id)
|
||||
assertThrows(IllegalStateException::class.java) { GogMaintenance.offlineInstaller(downloads, "pl-PL") }
|
||||
downloads.getJSONArray("installers").put(0, JSONObject("""{"id":"neutral","os":"windows","language":"Neutral","files":[{"downlink":"https://example.invalid/neutral"}]}"""))
|
||||
assertEquals("en", GogMaintenance.offlineInstaller(downloads, "en-US").id)
|
||||
assertEquals("neutral", GogMaintenance.offlineInstaller(downloads, "pl-PL").id)
|
||||
}
|
||||
|
||||
@Test fun incompleteOfflineExtractionCannotReplaceOrRemoveInstalledFiles() {
|
||||
val folder = temporary.newFolder()
|
||||
StoreGameSidecar(Store.GOG, "1", "Game", "game.exe").write(folder)
|
||||
val game = File(folder, "game.exe").apply { writeText("installed game") }
|
||||
val old = GogInstallRecord("1", "depot", files = JSONArray().put(JSONObject().put("path", game.name)
|
||||
.put("size", game.length()).put("md5", GogFiles.hash(game))))
|
||||
old.write(folder)
|
||||
val extracted = temporary.newFolder()
|
||||
File(extracted, "goggame-1.ico").writeText("ancillary file")
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, old, old.copy(source = "offline"), GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
|
||||
}
|
||||
assertEquals("installed game", game.readText())
|
||||
assertFalse(File(folder, "goggame-1.ico").exists())
|
||||
assertEquals("depot", GogInstallRecord.read(folder)!!.source)
|
||||
val migrated = old.copy(files = JSONArray())
|
||||
migrated.write(folder)
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, migrated, migrated.copy(source = "offline"), GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
|
||||
}
|
||||
assertEquals("installed game", game.readText())
|
||||
assertFalse(File(folder, "goggame-1.ico").exists())
|
||||
assertEquals("depot", GogInstallRecord.read(folder)!!.source)
|
||||
assertEquals(0, GogInstallRecord.read(folder)!!.files.length())
|
||||
}
|
||||
|
||||
@Test fun offlineRefreshCombinesRootPayloadAndAppPlaceholdersInBothLayouts() {
|
||||
for (nested in listOf(false, true)) {
|
||||
val folder = temporary.newFolder()
|
||||
val executable = if (nested) "app/game.exe" else "game.exe"
|
||||
StoreGameSidecar(Store.GOG, "1", "Game", executable).write(folder)
|
||||
val game = File(folder, executable).apply { parentFile!!.mkdirs(); writeText("old game") }
|
||||
val old = GogInstallRecord("1", "offline", files = JSONArray().put(JSONObject().put("path", executable)
|
||||
.put("size", game.length()).put("md5", GogFiles.hash(game))))
|
||||
old.write(folder)
|
||||
val extracted = temporary.newFolder()
|
||||
File(extracted, "game.exe").writeText("complete new game")
|
||||
File(extracted, "Data").mkdirs()
|
||||
File(extracted, "app/Data/SaveGame").mkdirs()
|
||||
File(extracted, "app/Data/SaveGame/dummy.txt").writeBytes(byteArrayOf())
|
||||
File(extracted, "tmp").mkdirs()
|
||||
File(extracted, "tmp/installer.exe").writeText("installer support")
|
||||
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, old, old, GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
|
||||
assertEquals("complete new game", game.readText())
|
||||
assertTrue(File(folder, (if (nested) "app/" else "") + "Data/SaveGame/dummy.txt").isFile)
|
||||
assertFalse(File(folder, "tmp").exists())
|
||||
assertTrue(GogInstallRecord.read(folder)!!.files.objects().any { it.getString("path") == executable })
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun offlineRefreshDefersDlcCleanupAndRecordPublicationUntilDepotCompletion() {
|
||||
val folder = temporary.newFolder()
|
||||
StoreGameSidecar(Store.GOG, "1", "Game", "base.exe").write(folder)
|
||||
val base = File(folder, "base.exe").apply { writeText("old base") }
|
||||
val dlc = File(folder, "dlc.bin").apply { writeText("old DLC") }
|
||||
val obsolete = File(folder, "old.bin").apply { writeText("obsolete") }
|
||||
val save = File(folder, "save.dat").apply { writeText("player progress") }
|
||||
fun entry(file: File, product: String) = JSONObject().put("path", file.name).put("size", file.length())
|
||||
.put("md5", GogFiles.hash(file)).put("product", product).put("offset", 0).put("remotePath", file.name)
|
||||
val old = GogInstallRecord("1", "depot", build = "old", products = listOf("1", "2"),
|
||||
files = JSONArray().put(entry(base, "1")).put(entry(dlc, "2")).put(entry(obsolete, "1")))
|
||||
old.write(folder)
|
||||
val recordFile = File(GogFiles.dir(folder), "installed.json")
|
||||
val record = recordFile.readText()
|
||||
val extracted = temporary.newFolder()
|
||||
val app = File(extracted, "app").apply { mkdirs() }
|
||||
File(app, "goggame-1.info").writeText("""{"buildId":"new"}""")
|
||||
val replacement = File(app, "base.exe").apply { writeText("new base") }
|
||||
val expectedDlc = File(temporary.newFolder(), "dlc.bin").apply { writeText("new DLC") }
|
||||
val target = old.copy(build = "new", files = JSONArray().put(entry(replacement, "1")).put(entry(expectedDlc, "2")))
|
||||
GogOffline.applyRefresh(GogMaintenance.Proposal(folder, old, target, GogOperation.REFRESH, 0, 0), extracted, null, AtomicBoolean(false))
|
||||
assertEquals("new base", base.readText())
|
||||
assertEquals("old DLC", dlc.readText())
|
||||
assertTrue(obsolete.isFile)
|
||||
assertEquals(record, recordFile.readText())
|
||||
val server = java.net.ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1"))
|
||||
val worker = Thread {
|
||||
server.accept().use { client ->
|
||||
val reader = client.getInputStream().bufferedReader()
|
||||
while (!reader.readLine().isNullOrEmpty()) Unit
|
||||
val content = expectedDlc.readBytes()
|
||||
client.getOutputStream().apply {
|
||||
write("HTTP/1.1 206 Partial Content\r\nContent-Length: ${content.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
write(content); flush()
|
||||
}
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
try {
|
||||
GogFallback.transfer(folder, JSONObject().put("files", target.files).put("oldFiles", old.files)
|
||||
.put("links", JSONObject().put("2", JSONArray().put("http://127.0.0.1:${server.localPort}"))), null, AtomicBoolean(false))
|
||||
assertEquals("new DLC", dlc.readText())
|
||||
assertFalse(obsolete.exists())
|
||||
assertEquals("player progress", save.readText())
|
||||
assertEquals(record, recordFile.readText())
|
||||
} finally { server.close(); worker.join(2000) }
|
||||
}
|
||||
|
||||
@Test fun authenticIdentityOverridesAStaleLegacyMarkerWithoutTreatingSchemaAsVersion() {
|
||||
val folder = temporary.newFolder()
|
||||
File(folder, "_gog_manifest.json").writeText("""{"buildId":"old"}""")
|
||||
File(folder, "goggame-1.id").writeText("""{"buildId":"patched"}""")
|
||||
File(folder, "goggame-1.info").writeText("""{"version":1}""")
|
||||
val record = GogInstallRecord.migrate(folder, StoreGameSidecar(Store.GOG, "1", "Game", "game.exe", installVersion = "old"))
|
||||
assertEquals("patched", record.build)
|
||||
assertEquals("", record.version)
|
||||
}
|
||||
|
||||
@Test fun authenticGenerationOneResolvesProductDepotsAndRetainsHashesAndBuild() {
|
||||
fun fixture(name: String) = JSONObject(javaClass.classLoader!!.getResource("gog/$name")!!.readText())
|
||||
val build = GogBuild("3301", "", 1, "", "https://example.invalid/repository.json")
|
||||
val requested = ArrayList<String>()
|
||||
val snapshot = GogContent.snapshot(GogInstallRecord("1207658940", "depot"), build, "unused") { url, _ ->
|
||||
requested.add(url)
|
||||
when {
|
||||
url == build.link -> fixture("rayman-gen1-repository.json")
|
||||
url.endsWith("a01f6fb8-55a8-4f33-bc5b-5f5d2f591775.json") -> fixture("rayman-gen1-neutral.json")
|
||||
url.endsWith("ec88140c-2589-41a0-bbf3-8fc1f215fe5a.json") -> fixture("rayman-gen1-english-excerpt.json")
|
||||
else -> error("Unexpected metadata: $url")
|
||||
}
|
||||
}
|
||||
assertEquals("3301", snapshot.build)
|
||||
assertEquals(1, snapshot.generation)
|
||||
assertEquals(4, snapshot.files.length())
|
||||
val support = snapshot.files.getJSONObject(0)
|
||||
assertEquals("support/1207658940/galaxy_rayman2_2.1.0.39.exe", support.getString("path"))
|
||||
assertEquals("ee2c247373733f29782395f1f92622f6", support.getString("md5"))
|
||||
val game = snapshot.files.getJSONObject(1)
|
||||
assertEquals("Data/World/Levels/Raycap/Raycap.snd", game.getString("path"))
|
||||
assertEquals(384206096L, game.getLong("offset"))
|
||||
assertEquals("1207658940/main.bin", game.getString("remotePath"))
|
||||
assertTrue(requested.drop(1).all { "/1207658940/windows/31847977/" in it })
|
||||
GogFiles.validate(snapshot.files, temporary.newFolder())
|
||||
}
|
||||
|
||||
@Test fun multipartPatchNamesVersionsLanguageAndChecksumsSurviveParsing() {
|
||||
val downloads = JSONObject("""{"patches":[
|
||||
{"id":"patch-1","name":"Patch A to B","version":"B","language":"pl","os":"windows","files":[
|
||||
{"id":"part0","filename":"patch_original.exe","downlink":"https://example.invalid/0","size":3,"md5":"abc"},
|
||||
{"id":"part1","filename":"patch_original-1.bin","downlink":"https://example.invalid/1","size":4}]},
|
||||
{"id":"linux","os":"linux","files":[{"downlink":"https://example.invalid/linux"}]}]}""")
|
||||
val patch = GogOfflineDownload.parse(downloads, "patches").single()
|
||||
assertEquals("Patch A to B", patch.name)
|
||||
assertEquals("B", patch.version)
|
||||
assertEquals("pl", patch.language)
|
||||
assertEquals(7, patch.size)
|
||||
assertEquals(listOf("patch_original.exe", "patch_original-1.bin"), patch.parts.map { it.name })
|
||||
assertEquals("abc", patch.parts.first().md5)
|
||||
assertEquals("patch_(52404)+special.exe", GogContent.downloadFilename("https://example.invalid/patch_%2852404%29+special.exe?token=temporary"))
|
||||
}
|
||||
|
||||
@Test fun pathsRejectTraversalSymlinksCaseCollisionsAndMetadataOverlap() {
|
||||
val folder = temporary.newFolder()
|
||||
for (path in listOf("../escape", "/absolute", "C:/file", "a/./file", "a//file")) {
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.inside(folder, path) }
|
||||
}
|
||||
val files = JSONArray("""[{"path":"Game.exe"},{"path":"game.exe"}]""")
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(files, folder) }
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":"Data/a"},{"path":"data/b"}]"""), folder) }
|
||||
File(folder, "Game.bin").writeText("original")
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":"game.bin"}]"""), folder) }
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":".droiddeck-store.json"}]"""), folder) }
|
||||
val outside = temporary.newFolder()
|
||||
try { Files.createSymbolicLink(File(folder, "link").toPath(), outside.toPath()) }
|
||||
catch (_: java.nio.file.FileSystemException) { return }
|
||||
assertThrows(IllegalArgumentException::class.java) { GogFiles.inside(folder, "link/game.exe") }
|
||||
}
|
||||
|
||||
@Test fun sameSizeCorruptionFailsVerificationAndLanguageVariantsRemainDistinct() {
|
||||
val folder = temporary.newFolder()
|
||||
val file = File(folder, "game.bin").apply { writeText("original") }
|
||||
val expected = JSONObject().put("path", file.name).put("size", file.length()).put("md5", GogFiles.hash(file))
|
||||
file.writeText("modified")
|
||||
assertFalse(GogFiles.matches(folder, expected))
|
||||
assertTrue(GogContent.languageSelected(listOf("*"), "zh-Hant"))
|
||||
assertFalse(GogContent.languageSelected(listOf("zh-Hans"), "zh-Hant"))
|
||||
assertTrue(GogContent.languageSelected(listOf("Polish"), "pl"))
|
||||
}
|
||||
|
||||
@Test fun persistedManifestsContainNoCredentialsOrTemporaryLinks() {
|
||||
val input = JSONObject("""{"buildId":"1","clientSecret":"secret","urls":[{"url":"https://example.invalid/?token=secret"}],
|
||||
"products":[{"productId":"2","clientSecret":"nested"}],"dependencies":["ISI"]}""")
|
||||
val text = GogContent.sanitize(input).toString()
|
||||
assertFalse(text.contains("secret"))
|
||||
assertFalse(text.contains("https://"))
|
||||
assertTrue(text.contains("ISI"))
|
||||
}
|
||||
|
||||
@Test fun interruptedExternalPatchRestoresRecoveryWithoutExecutingAgain() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "Patch recovery").apply { mkdirs() }
|
||||
try {
|
||||
val sidecar = StoreGameSidecar(Store.GOG, "recovery-test", "Patch recovery", "game.exe",
|
||||
args = listOf("--custom"), env = mapOf("SETTING" to "value"), cloud = false,
|
||||
achievements = false, state = StoreGameSidecar.STATE_UPDATING)
|
||||
sidecar.write(folder)
|
||||
val previous = sidecar.toJson().toString()
|
||||
GogFiles.write(GogFiles.journal(folder), JSONObject().put("operation", "PATCH").put("phase", "patch-applying"))
|
||||
val item = CatalogItem(Store.GOG, sidecar.id, sidecar.title, imageUrl = null, extra = mapOf(
|
||||
GogMaintenance.OPERATION to "PATCH", GogMaintenance.FOLDER to folder.path))
|
||||
GogMaintenance.restore(app, item)
|
||||
assertEquals(DownloadState.FAILED, DownloadQueue.entry(item.key)?.state)
|
||||
assertTrue(DownloadQueue.entry(item.key)!!.error!!.contains("recovery"))
|
||||
assertEquals(previous, StoreGameSidecar.read(folder)!!.toJson().toString())
|
||||
assertEquals("patch-applying", GogFiles.read(GogFiles.journal(folder))!!.getString("phase"))
|
||||
DownloadQueue.clear(app, item.key)
|
||||
} finally { folder.deleteRecursively() }
|
||||
}
|
||||
|
||||
@Test fun signedOutCheckRemainsAFailureInsteadOfCurrent() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
com.droiddeck.launcher.stores.StoreAccounts.clear(app, Store.GOG)
|
||||
GogMaintenance.reset()
|
||||
val folder = temporary.newFolder()
|
||||
val game = com.droiddeck.launcher.stores.InstalledStoreGame(
|
||||
StoreGameSidecar(Store.GOG, "signed-out-check", "Check", "game.exe", installVersion = "opaque-build"), folder)
|
||||
GogMaintenance.check(app, game, force = true)
|
||||
val deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(5)
|
||||
while (System.nanoTime() < deadline) {
|
||||
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||
if (GogMaintenance.checks[game.sidecar.id]?.state == GogMaintenance.State.FAILED) break
|
||||
Thread.sleep(10)
|
||||
}
|
||||
assertEquals(GogMaintenance.State.FAILED, GogMaintenance.checks[game.sidecar.id]?.state)
|
||||
assertTrue(GogMaintenance.checks[game.sidecar.id]!!.reason.contains("Sign in"))
|
||||
}
|
||||
|
||||
@Test fun pauseBeforeInstallerClaimCannotStartExternalApplication() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val ready = java.util.concurrent.CountDownLatch(1)
|
||||
val proceed = java.util.concurrent.CountDownLatch(1)
|
||||
val finished = java.util.concurrent.CountDownLatch(1)
|
||||
val applied = AtomicBoolean(false)
|
||||
val item = com.droiddeck.launcher.stores.download.DownloadEntry(Store.GOG, "installer-claim", "Installer claim")
|
||||
DownloadQueue.enqueue(app, item) {
|
||||
object : DownloadQueue.DownloadJob {
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
ready.countDown()
|
||||
try {
|
||||
check(proceed.await(5, java.util.concurrent.TimeUnit.SECONDS))
|
||||
handle.interruptible(false)
|
||||
applied.set(true)
|
||||
return null
|
||||
} finally { finished.countDown() }
|
||||
}
|
||||
override fun cancel(deleteFiles: Boolean) {}
|
||||
}
|
||||
}
|
||||
try {
|
||||
assertTrue(ready.await(5, java.util.concurrent.TimeUnit.SECONDS))
|
||||
DownloadQueue.pause(item.key)
|
||||
proceed.countDown()
|
||||
assertTrue(finished.await(5, java.util.concurrent.TimeUnit.SECONDS))
|
||||
assertFalse(applied.get())
|
||||
} finally {
|
||||
proceed.countDown()
|
||||
val deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(5)
|
||||
while (DownloadQueue.entry(item.key)?.state == DownloadState.RUNNING && System.nanoTime() < deadline) Thread.sleep(10)
|
||||
DownloadQueue.clear(app, item.key)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun fileFallbackVerifiesRemoteBytesAndPreservesOriginalOnCorruption() {
|
||||
val folder = temporary.newFolder()
|
||||
val content = "verified remote content".toByteArray()
|
||||
val original = File(folder, "game.bin").apply { writeText("local data") }
|
||||
val server = java.net.ServerSocket(0, 10, java.net.InetAddress.getByName("127.0.0.1"))
|
||||
var reply = content
|
||||
var transferred = 0
|
||||
val worker = Thread {
|
||||
while (!server.isClosed) {
|
||||
val client = try { server.accept() } catch (_: java.io.IOException) { break }
|
||||
client.use {
|
||||
val reader = it.getInputStream().bufferedReader()
|
||||
while (!reader.readLine().isNullOrEmpty()) Unit
|
||||
it.getOutputStream().apply {
|
||||
write("HTTP/1.1 206 Partial Content\r\nContent-Length: ${reply.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
write(reply); flush(); transferred += reply.size
|
||||
}
|
||||
}
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
try {
|
||||
val expected = File(folder, "expected").apply { writeBytes(content) }
|
||||
val file = JSONObject().put("path", "game.bin").put("size", content.size).put("md5", GogFiles.hash(expected))
|
||||
.put("product", "1").put("offset", 0).put("remotePath", "data")
|
||||
val plan = JSONObject().put("files", JSONArray().put(file)).put("links", JSONObject().put("1", JSONArray().put("http://127.0.0.1:${server.localPort}")))
|
||||
reply = ByteArray(content.size) { 65 }
|
||||
assertThrows(IllegalStateException::class.java) { GogFallback.transfer(folder, plan, null, AtomicBoolean(false)) }
|
||||
assertEquals("local data", original.readText())
|
||||
reply = content
|
||||
GogFallback.transfer(folder, plan, null, AtomicBoolean(false))
|
||||
assertArrayEquals(content, original.readBytes())
|
||||
val before = transferred
|
||||
GogFallback.transfer(folder, plan, null, AtomicBoolean(false))
|
||||
assertEquals(before, transferred)
|
||||
} finally { server.close(); worker.join(2000) }
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,25 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.maintenance.RecoveryState
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class ItchStagingTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@@ -34,18 +46,16 @@ class ItchStagingTest {
|
||||
assertTrue(staged.listFiles().orEmpty().all { it.isDirectory && it.listFiles().orEmpty().isEmpty() })
|
||||
}
|
||||
|
||||
@Test fun aFileReplacingADirectoryAndTheOtherWayRound() {
|
||||
@Test fun aFileDirectoryCollisionFailsWithoutDeletingExistingData() {
|
||||
val game = tmp.newFolder("game")
|
||||
val staged = tmp.newFolder("staged")
|
||||
file(game, "a/inner.txt", "old")
|
||||
file(game, "b", "old")
|
||||
file(staged, "a", "new")
|
||||
file(staged, "b/inner.txt", "new")
|
||||
ItchStaging.merge(staged, game)
|
||||
assertTrue(File(game, "a").isFile)
|
||||
assertEquals("new", File(game, "a").readText())
|
||||
assertEquals("new", File(game, "b/inner.txt").readText())
|
||||
assertFalse(File(game, "a/inner.txt").exists())
|
||||
assertThrows(IllegalArgumentException::class.java) { ItchStaging.merge(staged, game) }
|
||||
assertEquals("old", File(game, "a/inner.txt").readText())
|
||||
assertEquals("old", File(game, "b").readText())
|
||||
}
|
||||
|
||||
@Test fun deletingFollowsNoLinkOutOfTheTree() {
|
||||
@@ -82,4 +92,307 @@ class ItchStagingTest {
|
||||
assertEquals("record", File(game, ".droiddeck-store.json").readText())
|
||||
assertEquals("nested", File(game, "sub/.droiddeck-store.json").readText())
|
||||
}
|
||||
|
||||
@Test fun managedCommitRepairsCorruptionRemovesOnlyUntouchedObsoleteFilesAndKeepsSaves() {
|
||||
val game = tmp.newFolder("managed-game")
|
||||
val staged = tmp.newFolder("managed-stage")
|
||||
file(game, "bin/game.exe", "corrupted")
|
||||
file(game, "data/removed.dat", "publisher-old")
|
||||
file(game, "saves/slot1.sav", "my-save")
|
||||
file(game, "data/user.ini", "my-config")
|
||||
file(staged, "bin/game.exe", "publisher-new")
|
||||
file(staged, "data/new.dat", "new")
|
||||
val previous = ItchStaging.inventory(tmp.newFolder("old-inventory")).toMutableMap()
|
||||
val oldFiles = tmp.newFolder("old-publisher")
|
||||
file(oldFiles, "bin/game.exe", "publisher-prior")
|
||||
file(oldFiles, "data/removed.dat", "publisher-old")
|
||||
previous.putAll(ItchStaging.inventory(oldFiles))
|
||||
val next = ItchStaging.commit(staged, game, previous)
|
||||
assertEquals("publisher-new", File(game, "bin/game.exe").readText())
|
||||
assertFalse(File(game, "data/removed.dat").exists())
|
||||
assertEquals("my-save", File(game, "saves/slot1.sav").readText())
|
||||
assertEquals("my-config", File(game, "data/user.ini").readText())
|
||||
assertEquals("new", File(game, "data/new.dat").readText())
|
||||
ItchStaging.writeInventory(game, next)
|
||||
assertEquals(next, ItchStaging.readInventory(game))
|
||||
}
|
||||
|
||||
@Test fun interruptedCommitResumesFromPinnedInventoryAndCompletesObsoleteCleanup() {
|
||||
val game = tmp.newFolder("resume-game")
|
||||
val staged = tmp.newFolder("resume-stage")
|
||||
file(game, "old.txt", "old")
|
||||
file(staged, "a.txt", "new-a")
|
||||
file(staged, "b.txt", "new-b")
|
||||
val previous = ItchStaging.inventory(game)
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ItchStaging.commit(staged, game, previous, afterEntry = { if (it == 1) error("simulated interruption") })
|
||||
}
|
||||
assertTrue(ItchStaging.recover(game))
|
||||
val next = ItchStaging.commit(staged, game, previous)
|
||||
assertEquals("new-a", File(game, "a.txt").readText())
|
||||
assertEquals("new-b", File(game, "b.txt").readText())
|
||||
assertFalse(File(game, "old.txt").exists())
|
||||
assertEquals(setOf("a.txt", "b.txt"), next.keys)
|
||||
assertFalse(ItchStaging.recover(game))
|
||||
}
|
||||
|
||||
@Test fun progressIsAppendedAndTornTrailingRecordIsDiscardedBeforeResume() {
|
||||
val game = tmp.newFolder("progress-game")
|
||||
val staged = tmp.newFolder("progress-stage")
|
||||
file(staged, "a.txt", "a")
|
||||
file(staged, "b.txt", "b")
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ItchStaging.commit(staged, game, emptyMap(), afterEntry = { if (it == 1) error("simulated interruption") })
|
||||
}
|
||||
val metadata = File(game, ".droiddeck-maintenance")
|
||||
val plan = File(metadata, "itch-commit.json")
|
||||
val progress = File(metadata, "itch-commit-progress.jsonl")
|
||||
val planBefore = plan.readText()
|
||||
assertFalse(JSONObject(planBefore).has("done"))
|
||||
assertTrue(progress.readText().contains("\"path\""))
|
||||
progress.appendText("{\"path\":\"torn")
|
||||
|
||||
assertTrue(ItchStaging.recover(game))
|
||||
assertFalse(progress.readText().contains("torn"))
|
||||
ItchStaging.commit(staged, game, emptyMap())
|
||||
assertEquals("a", File(game, "a.txt").readText())
|
||||
assertEquals("b", File(game, "b.txt").readText())
|
||||
assertFalse(plan.exists())
|
||||
assertFalse(progress.exists())
|
||||
}
|
||||
|
||||
@Test fun completeMalformedProgressRecordFailsClosed() {
|
||||
val game = tmp.newFolder("bad-progress-game")
|
||||
val staged = tmp.newFolder("bad-progress-stage")
|
||||
file(staged, "a.txt", "a")
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ItchStaging.commit(staged, game, emptyMap(), afterEntry = { error("simulated interruption") })
|
||||
}
|
||||
val progress = File(game, ".droiddeck-maintenance/itch-commit-progress.jsonl")
|
||||
progress.appendText("{bad}\n")
|
||||
assertThrows(IllegalStateException::class.java) { ItchStaging.recover(game) }
|
||||
}
|
||||
|
||||
@Test fun legacyDoneJournalMigratesToAppendOnlyProgress() {
|
||||
val game = tmp.newFolder("legacy-journal-game")
|
||||
val staged = tmp.newFolder("legacy-journal-stage")
|
||||
file(staged, "a.txt", "a")
|
||||
file(staged, "b.txt", "b")
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ItchStaging.commit(staged, game, emptyMap(), afterEntry = { if (it == 1) error("simulated interruption") })
|
||||
}
|
||||
val metadata = File(game, ".droiddeck-maintenance")
|
||||
val journal = File(metadata, "itch-commit.json")
|
||||
val progress = File(metadata, "itch-commit-progress.jsonl")
|
||||
val old = JSONObject(journal.readText())
|
||||
val done = JSONObject().put("a.txt", true)
|
||||
journal.writeText(JSONObject().put("schema", 1).put("next", old.getJSONObject("next"))
|
||||
.put("obsolete", old.getJSONObject("obsolete")).put("done", done).toString())
|
||||
progress.delete()
|
||||
|
||||
ItchStaging.commit(staged, game, emptyMap())
|
||||
assertEquals("a", File(game, "a.txt").readText())
|
||||
assertEquals("b", File(game, "b.txt").readText())
|
||||
assertFalse(journal.exists())
|
||||
assertFalse(progress.exists())
|
||||
}
|
||||
|
||||
@Test fun backupMetadataUsesCanonicalInstallWhenParentIsSymlinked() {
|
||||
val actualParent = tmp.newFolder("actual-install-parent")
|
||||
val aliasParent = File(tmp.root, "linked-install-parent")
|
||||
java.nio.file.Files.createSymbolicLink(aliasParent.toPath(), actualParent.toPath())
|
||||
val game = File(aliasParent, "game").also { assertTrue(it.mkdirs()) }
|
||||
val staged = tmp.newFolder("canonical-stage")
|
||||
file(game, "bin/game.dat", "old")
|
||||
file(staged, "bin/game.dat", "new")
|
||||
val previous = ItchStaging.inventory(game)
|
||||
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ItchStaging.commit(staged, game, previous, afterEntry = { error("simulated interruption") })
|
||||
}
|
||||
val canonicalGame = File(actualParent, "game")
|
||||
assertTrue(File(canonicalGame, ".droiddeck-maintenance/itch-backups/bin/game.dat").isFile)
|
||||
assertTrue(ItchStaging.recover(game))
|
||||
ItchStaging.commit(staged, game, previous)
|
||||
assertEquals("new", File(canonicalGame, "bin/game.dat").readText())
|
||||
}
|
||||
|
||||
@Test fun failedInventoryPublicationKeepsCommitJournalUntilResume() {
|
||||
val game = tmp.newFolder("inventory-publication-game")
|
||||
val staged = tmp.newFolder("inventory-publication-stage")
|
||||
file(staged, "game.exe", "publisher")
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ItchStaging.commit(staged, game, emptyMap(), onCommitted = { error("simulated inventory failure") })
|
||||
}
|
||||
assertTrue(ItchStaging.recover(game))
|
||||
val next = ItchStaging.commit(staged, game, emptyMap(), onCommitted = { ItchStaging.writeInventory(game, it) })
|
||||
assertEquals("publisher", File(game, "game.exe").readText())
|
||||
assertEquals(next, ItchStaging.readInventory(game))
|
||||
assertFalse(ItchStaging.recover(game))
|
||||
}
|
||||
|
||||
@Test fun unmanagedCollisionPreservesUserFile() {
|
||||
val game = tmp.newFolder("collision-game")
|
||||
val staged = tmp.newFolder("collision-stage")
|
||||
file(game, "saves/slot1.sav", "my-save")
|
||||
file(staged, "saves/slot1.sav", "archive-file")
|
||||
assertThrows(IllegalArgumentException::class.java) { ItchStaging.commit(staged, game, emptyMap()) }
|
||||
assertEquals("my-save", File(game, "saves/slot1.sav").readText())
|
||||
assertFalse(ItchStaging.recover(game))
|
||||
}
|
||||
|
||||
@Test fun legacyInventoryBootstrapRequiresAnAbsentInventoryAndExactTarget() {
|
||||
val targetStage = tmp.newFolder("legacy-target")
|
||||
file(targetStage, "game.exe", "publisher build")
|
||||
file(targetStage, "notes.txt", "publisher notes")
|
||||
val target = ItchStaging.inventory(targetStage)
|
||||
|
||||
assertEquals(target, ItchStaging.previousInventory(null, target, exactLegacyTarget = true, selectedExe = "game.exe"))
|
||||
assertEquals(emptyMap<String, String>(), ItchStaging.previousInventory(null, target, exactLegacyTarget = false, selectedExe = "game.exe"))
|
||||
assertEquals(emptyMap<String, String>(), ItchStaging.previousInventory(emptyMap(), target, exactLegacyTarget = true, selectedExe = "game.exe"))
|
||||
assertEquals(mapOf("notes.txt" to target.getValue("notes.txt")),
|
||||
ItchStaging.previousInventory(target, target - "game.exe", exactLegacyTarget = true, selectedExe = "game.exe"))
|
||||
|
||||
val game = tmp.newFolder("legacy-game")
|
||||
file(game, "game.exe", "corrupted publisher build")
|
||||
file(game, "user-notes.txt", "keep")
|
||||
ItchStaging.commit(targetStage, game,
|
||||
ItchStaging.previousInventory(null, target, exactLegacyTarget = true, selectedExe = "game.exe"))
|
||||
assertEquals("publisher build", File(game, "game.exe").readText())
|
||||
assertEquals("keep", File(game, "user-notes.txt").readText())
|
||||
|
||||
val unknownBuild = tmp.newFolder("unknown-legacy-game")
|
||||
val unknownTargetStage = tmp.newFolder("unknown-legacy-target")
|
||||
file(unknownTargetStage, "game.exe", "publisher build")
|
||||
file(unknownTargetStage, "notes.txt", "publisher notes")
|
||||
file(unknownBuild, "game.exe", "unknown installed build")
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
ItchStaging.commit(unknownTargetStage, unknownBuild,
|
||||
ItchStaging.previousInventory(null, target, exactLegacyTarget = false, selectedExe = "game.exe"))
|
||||
}
|
||||
assertEquals("unknown installed build", File(unknownBuild, "game.exe").readText())
|
||||
assertFalse(ItchStaging.recover(unknownBuild))
|
||||
|
||||
val inventoryState = tmp.newFolder("inventory-state")
|
||||
assertNull(ItchStaging.readInventoryIfPresent(inventoryState))
|
||||
ItchStaging.writeInventory(inventoryState, emptyMap())
|
||||
assertEquals(emptyMap<String, String>(), ItchStaging.readInventoryIfPresent(inventoryState))
|
||||
}
|
||||
|
||||
@Test fun publisherUserDataPlaceholdersAndEmptyDirectoriesAreInstalledAndManaged() {
|
||||
val game = tmp.newFolder("publisher-user-data-game")
|
||||
val staged = tmp.newFolder("publisher-user-data-stage")
|
||||
file(staged, "profiles/default/config.ini", "publisher defaults")
|
||||
file(staged, "saves/default.sav", "")
|
||||
File(staged, "data/required-empty").mkdirs()
|
||||
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ItchStaging.commit(staged, game, emptyMap(), afterEntry = { if (it == 2) error("simulated interruption") })
|
||||
}
|
||||
assertTrue(ItchStaging.recover(game))
|
||||
val next = ItchStaging.commit(staged, game, emptyMap())
|
||||
|
||||
assertEquals("publisher defaults", File(game, "profiles/default/config.ini").readText())
|
||||
assertTrue(File(game, "saves/default.sav").isFile)
|
||||
assertEquals(0L, File(game, "saves/default.sav").length())
|
||||
assertTrue(File(game, "data/required-empty").isDirectory)
|
||||
assertTrue("profiles/default/config.ini" in next)
|
||||
assertTrue("saves/default.sav" in next)
|
||||
assertEquals("<directory>", next["data/required-empty/"])
|
||||
ItchStaging.writeInventory(game, next)
|
||||
assertEquals(next, ItchStaging.readInventory(game))
|
||||
assertFalse(ItchStaging.recover(game))
|
||||
}
|
||||
|
||||
@Test fun locallyModifiedManagedProfileIsPreservedByRefusingReplacement() {
|
||||
val game = tmp.newFolder("modified-save-game")
|
||||
val oldPublisher = tmp.newFolder("modified-save-old")
|
||||
val staged = tmp.newFolder("modified-save-stage")
|
||||
file(oldPublisher, "profiles/settings.ini", "publisher defaults")
|
||||
file(game, "profiles/settings.ini", "user settings")
|
||||
file(staged, "profiles/settings.ini", "new publisher defaults")
|
||||
val previous = ItchStaging.inventory(oldPublisher)
|
||||
|
||||
assertThrows(IllegalArgumentException::class.java) { ItchStaging.commit(staged, game, previous) }
|
||||
|
||||
assertEquals("user settings", File(game, "profiles/settings.ini").readText())
|
||||
}
|
||||
|
||||
@Test fun extractedPayloadAndBackupExtraSpaceAreAddedWithoutOverflow() {
|
||||
val stage = tmp.newFolder("space-stage")
|
||||
file(stage, "profiles/default.ini", "1234567890")
|
||||
file(stage, "saves/default.sav", "")
|
||||
assertEquals(10L, ItchStaging.regularFileBytes(stage))
|
||||
assertEquals(38L, ItchStaging.additionalBytesRequired(10L, 28L))
|
||||
assertEquals(Long.MAX_VALUE, ItchStaging.additionalBytesRequired(Long.MAX_VALUE - 1, 2))
|
||||
}
|
||||
|
||||
@Test fun aDoneJournalEntryIsRehashedBeforeResumeSkipsIt() {
|
||||
val game = tmp.newFolder("corrupt-resume-game")
|
||||
val staged = tmp.newFolder("corrupt-resume-stage")
|
||||
file(game, "old.txt", "old")
|
||||
file(staged, "a.txt", "new-a")
|
||||
file(staged, "b.txt", "new-b")
|
||||
val previous = ItchStaging.inventory(game)
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ItchStaging.commit(staged, game, previous, afterEntry = { if (it == 2) error("simulated interruption") })
|
||||
}
|
||||
file(game, "a.txt", "tampered")
|
||||
file(staged, "a.txt", "new-a")
|
||||
ItchStaging.commit(staged, game, previous)
|
||||
assertEquals("new-a", File(game, "a.txt").readText())
|
||||
assertEquals("new-b", File(game, "b.txt").readText())
|
||||
}
|
||||
|
||||
@Test fun corruptOrSymlinkedCommitJournalsFailClosed() {
|
||||
val game = tmp.newFolder("journal-game")
|
||||
val staged = tmp.newFolder("journal-stage")
|
||||
val metadata = File(game, ".droiddeck-maintenance").also { it.mkdirs() }
|
||||
file(game, "user.txt", "keep")
|
||||
file(staged, "user.txt", "publisher")
|
||||
val journal = File(metadata, "itch-commit.json")
|
||||
journal.writeText("{")
|
||||
assertThrows(IllegalStateException::class.java) { ItchStaging.commit(staged, game, emptyMap()) }
|
||||
assertThrows(IllegalStateException::class.java) { ItchStaging.recover(game) }
|
||||
assertEquals("keep", File(game, "user.txt").readText())
|
||||
journal.delete()
|
||||
val outside = file(tmp.newFolder("journal-outside"), "outside.json", "{}")
|
||||
java.nio.file.Files.createSymbolicLink(journal.toPath(), outside.toPath())
|
||||
assertThrows(IllegalStateException::class.java) { ItchStaging.commit(staged, game, emptyMap()) }
|
||||
assertThrows(IllegalStateException::class.java) { ItchStaging.recover(game) }
|
||||
assertEquals("{}", outside.readText())
|
||||
assertEquals("keep", File(game, "user.txt").readText())
|
||||
journal.delete()
|
||||
metadata.delete()
|
||||
val outsideMetadata = tmp.newFolder("outside-metadata")
|
||||
file(outsideMetadata, "itch-commit.json", "{}")
|
||||
java.nio.file.Files.createSymbolicLink(metadata.toPath(), outsideMetadata.toPath())
|
||||
assertThrows(IllegalArgumentException::class.java) { ItchStaging.recover(game) }
|
||||
assertEquals("{}", File(outsideMetadata, "itch-commit.json").readText())
|
||||
}
|
||||
|
||||
@Test fun corruptManagedInventoryFailsClosed() {
|
||||
val game = tmp.newFolder("inventory-game")
|
||||
val metadata = File(game, ".droiddeck-maintenance").also { it.mkdirs() }
|
||||
file(game, "publisher.txt", "keep")
|
||||
File(metadata, "itch-inventory.json").writeText("{\"../outside.txt\":\"bad\"}")
|
||||
assertThrows(IllegalArgumentException::class.java) { ItchStaging.readInventory(game) }
|
||||
assertEquals("keep", File(game, "publisher.txt").readText())
|
||||
}
|
||||
|
||||
@Test fun corruptInventoryMakesApplyingRecoveryNeedAttention() {
|
||||
val folder = tmp.newFolder("corrupt-recovery-inventory").canonicalFile
|
||||
val sidecar = StoreGameSidecar(Store.ITCH, "game", "Example", "game.exe")
|
||||
sidecar.write(folder)
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
StoreMaintenance.register(ItchMaintenanceAdapter)
|
||||
val operation = StoreMaintenance.operationFile(folder)
|
||||
operation.parentFile.mkdirs()
|
||||
operation.writeText(JSONObject().put("schema", 1).put("store", Store.ITCH.id)
|
||||
.put("id", sidecar.id).put("folder", folder.path).put("phase", "applying").toString())
|
||||
File(operation.parentFile, "itch-inventory.json").writeText("{")
|
||||
|
||||
assertEquals(RecoveryState.NEEDS_ATTENTION,
|
||||
StoreMaintenance.recovery(RuntimeEnvironment.getApplication(), game).state)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package com.droiddeck.launcher.stores.maintenance
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
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 org.json.JSONObject
|
||||
import org.json.JSONArray
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class StoreMaintenanceTest {
|
||||
@get:Rule val temporary = TemporaryFolder()
|
||||
|
||||
private val adapter = object : StoreMaintenanceAdapter {
|
||||
override val store = Store.EPIC
|
||||
override fun capabilities(game: InstalledStoreGame) = setOf(MaintenanceAction.UPDATE)
|
||||
override fun check(context: Context, game: InstalledStoreGame) = MaintenanceCheck(MaintenanceCheckState.CURRENT)
|
||||
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction) = error("unused")
|
||||
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal) = true
|
||||
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) = Unit
|
||||
}
|
||||
|
||||
@Test fun operationPinsFolderTargetAndFullSidecarBeforeApply() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val folder = temporary.newFolder().canonicalFile
|
||||
val sidecar = StoreGameSidecar(Store.EPIC, "app", "Example", "bin/game.exe", args = listOf("--user-value"),
|
||||
env = mapOf("CUSTOM_SETTING" to "kept"), installedAt = 1234L, extra = mapOf("channel" to "test"))
|
||||
sidecar.write(folder)
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
StoreMaintenance.register(adapter)
|
||||
|
||||
StoreMaintenance.enqueue(app, game, MaintenanceProposal(folder, sidecar, "version 2", MaintenanceAction.UPDATE,
|
||||
downloadBytes = 42, diskBytes = 84, target = JSONObject().put("schema", 1).put("build", "2")))
|
||||
|
||||
val journal = StoreMaintenance.readOperation(folder)!!
|
||||
assertEquals(folder.path, journal.getString("folder"))
|
||||
assertEquals("app", journal.getString("id"))
|
||||
assertEquals("queued", journal.getString("phase"))
|
||||
assertEquals("2", journal.getJSONObject("target").getString("build"))
|
||||
val before = StoreGameSidecar.parse(journal.getJSONObject("before").toString())!!
|
||||
assertEquals(sidecar.args, before.args)
|
||||
assertEquals(sidecar.env, before.env)
|
||||
assertEquals(sidecar.installedAt, before.installedAt)
|
||||
assertEquals(sidecar.extra, before.extra)
|
||||
}
|
||||
|
||||
@Test fun failedApplyLeavesLaunchExcludedRecoveryStateAndJournal() {
|
||||
val folder = temporary.newFolder().canonicalFile
|
||||
val sidecar = StoreGameSidecar(Store.EPIC, "app", "Example", "bin/game.exe")
|
||||
sidecar.write(folder)
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
StoreMaintenance.register(adapter)
|
||||
StoreMaintenance.enqueue(RuntimeEnvironment.getApplication(), game,
|
||||
MaintenanceProposal(folder, sidecar, "version 2", MaintenanceAction.UPDATE, target = JSONObject().put("schema", 1)))
|
||||
|
||||
runCatching {
|
||||
StoreMaintenance.withApplyLease(game) {
|
||||
error("simulated interrupted apply")
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(folder)!!.state)
|
||||
assertEquals("applying", StoreMaintenance.readOperation(folder)!!.getString("phase"))
|
||||
assertEquals(RecoveryState.NEEDS_ATTENTION, StoreMaintenance.recovery(RuntimeEnvironment.getApplication(), game).state)
|
||||
assertTrue(StoreMaintenance.launchExcluded(game))
|
||||
assertTrue(StoreMaintenance.operationFile(folder).isFile)
|
||||
}
|
||||
|
||||
@Test fun queuedOperationDoesNotMarkTheInstallAsApplying() {
|
||||
val folder = temporary.newFolder().canonicalFile
|
||||
val sidecar = StoreGameSidecar(Store.EPIC, "app", "Example", "bin/game.exe")
|
||||
sidecar.write(folder)
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
StoreMaintenance.register(adapter)
|
||||
StoreMaintenance.enqueue(RuntimeEnvironment.getApplication(), game,
|
||||
MaintenanceProposal(folder, sidecar, "version 2", MaintenanceAction.UPDATE, target = JSONObject().put("schema", 1)))
|
||||
|
||||
assertFalse(StoreMaintenance.launchExcluded(game))
|
||||
assertEquals(RecoveryState.RESUMABLE, StoreMaintenance.recovery(RuntimeEnvironment.getApplication(), game).state)
|
||||
}
|
||||
|
||||
@Test fun failedQueueSubmissionClearsOnlyItsNewQueuedJournalAndRethrowsOriginalError() {
|
||||
val folder = temporary.newFolder().canonicalFile
|
||||
val sidecar = StoreGameSidecar(Store.EPIC, "enqueue-failure", "Example", "bin/game.exe")
|
||||
sidecar.write(folder)
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
val failure = IllegalStateException("queue rejected")
|
||||
StoreMaintenance.register(object : StoreMaintenanceAdapter {
|
||||
override val store = Store.EPIC
|
||||
override fun capabilities(game: InstalledStoreGame) = setOf(MaintenanceAction.UPDATE)
|
||||
override fun check(context: Context, game: InstalledStoreGame) = MaintenanceCheck()
|
||||
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction) = error("unused")
|
||||
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean { throw failure }
|
||||
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) = Unit
|
||||
})
|
||||
val proposal = MaintenanceProposal(folder, sidecar, "target", MaintenanceAction.UPDATE,
|
||||
target = JSONObject().put("schema", 1).put("build", "target"))
|
||||
|
||||
val thrown = runCatching { StoreMaintenance.enqueue(RuntimeEnvironment.getApplication(), game, proposal) }.exceptionOrNull()
|
||||
|
||||
assertSame(failure, thrown)
|
||||
assertNull(StoreMaintenance.readOperation(folder))
|
||||
}
|
||||
|
||||
@Test fun failedQueueSubmissionPreservesJournalThatHasAdvancedFromQueued() {
|
||||
val folder = temporary.newFolder().canonicalFile
|
||||
val sidecar = StoreGameSidecar(Store.EPIC, "enqueue-advanced", "Example", "bin/game.exe")
|
||||
sidecar.write(folder)
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
val failure = IllegalStateException("queue response lost")
|
||||
StoreMaintenance.register(object : StoreMaintenanceAdapter {
|
||||
override val store = Store.EPIC
|
||||
override fun capabilities(game: InstalledStoreGame) = setOf(MaintenanceAction.UPDATE)
|
||||
override fun check(context: Context, game: InstalledStoreGame) = MaintenanceCheck()
|
||||
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction) = error("unused")
|
||||
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean {
|
||||
val file = StoreMaintenance.operationFile(game.folder)
|
||||
file.writeText(JSONObject(file.readText()).put("phase", "download").toString())
|
||||
throw failure
|
||||
}
|
||||
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) = Unit
|
||||
})
|
||||
val proposal = MaintenanceProposal(folder, sidecar, "target", MaintenanceAction.UPDATE,
|
||||
target = JSONObject().put("schema", 1).put("build", "target"))
|
||||
|
||||
val thrown = runCatching { StoreMaintenance.enqueue(RuntimeEnvironment.getApplication(), game, proposal) }.exceptionOrNull()
|
||||
|
||||
assertSame(failure, thrown)
|
||||
assertEquals("download", StoreMaintenance.readOperation(folder)!!.getString("phase"))
|
||||
}
|
||||
|
||||
@Test fun queueRaceRejectionClearsOnlyMaintenanceJournalAndKeepsExistingSavedJob() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val folder = temporary.newFolder().canonicalFile
|
||||
val sidecar = StoreGameSidecar(Store.EPIC, "queue-race", "Example", "bin/game.exe")
|
||||
sidecar.write(folder)
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
val existing = CatalogItem(Store.EPIC, sidecar.id, "Existing job", imageUrl = null, owned = true)
|
||||
val maintenance = CatalogItem(Store.EPIC, sidecar.id, "Maintenance job", imageUrl = null, owned = true)
|
||||
val key = DownloadEntry(Store.EPIC, sidecar.id, existing.title).key
|
||||
fun job() = object : DownloadQueue.DownloadJob {
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? = null
|
||||
override fun cancel(deleteFiles: Boolean) = Unit
|
||||
}
|
||||
DownloadQueue.holdPaused(key)
|
||||
StoreMaintenance.register(object : StoreMaintenanceAdapter {
|
||||
override val store = Store.EPIC
|
||||
override fun capabilities(game: InstalledStoreGame) = setOf(MaintenanceAction.UPDATE)
|
||||
override fun check(context: Context, game: InstalledStoreGame) = MaintenanceCheck()
|
||||
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction) = error("unused")
|
||||
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal): Boolean {
|
||||
SavedQueue.remember(context, existing, null)
|
||||
DownloadQueue.enqueue(context, DownloadEntry(Store.EPIC, sidecar.id, existing.title), ::job)
|
||||
return DownloadQueue.enqueueIfIdle(context, DownloadEntry(Store.EPIC, sidecar.id, maintenance.title), onAccepted = {
|
||||
SavedQueue.remember(context, maintenance, null)
|
||||
}, factory = ::job)
|
||||
}
|
||||
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) = Unit
|
||||
})
|
||||
val proposal = MaintenanceProposal(folder, sidecar, "target", MaintenanceAction.UPDATE,
|
||||
target = JSONObject().put("schema", 1).put("build", "target"))
|
||||
|
||||
assertTrue(runCatching { StoreMaintenance.enqueue(app, game, proposal) }.isFailure)
|
||||
|
||||
assertNull(StoreMaintenance.readOperation(folder))
|
||||
assertEquals(DownloadState.PAUSED, DownloadQueue.entry(key)?.state)
|
||||
val saved = File(app.filesDir, "store-queue.json")
|
||||
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
var existingSaved = false
|
||||
while (!existingSaved && System.nanoTime() < until) {
|
||||
existingSaved = runCatching {
|
||||
val rows = JSONArray(saved.readText())
|
||||
(0 until rows.length()).any { i -> rows.getJSONObject(i).getJSONObject("item").getString("title") == existing.title }
|
||||
}.getOrDefault(false)
|
||||
if (!existingSaved) Thread.sleep(10)
|
||||
}
|
||||
assertTrue("rejected maintenance must not replace the active queue's saved item", existingSaved)
|
||||
DownloadQueue.clear(app, key)
|
||||
}
|
||||
|
||||
@Test fun uninstallAdmissionAndMaintenanceAdmissionCannotOverlapOrRecreateADeletedInstall() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val folder = temporary.newFolder().canonicalFile
|
||||
val sidecar = StoreGameSidecar(Store.EPIC, "uninstall-race", "Example", "bin/game.exe")
|
||||
sidecar.write(folder)
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
val proposal = MaintenanceProposal(folder, sidecar, "target", MaintenanceAction.UPDATE,
|
||||
target = JSONObject().put("schema", 1).put("build", "target"))
|
||||
StoreMaintenance.register(adapter)
|
||||
|
||||
assertTrue(StoreMaintenance.beginUninstall(game))
|
||||
assertTrue(game.key in StoresState.uninstalling)
|
||||
val prepareFailure = runCatching { StoreMaintenance.prepare(app, game, MaintenanceAction.UPDATE) }.exceptionOrNull()
|
||||
assertTrue(prepareFailure?.message.orEmpty().contains("being uninstalled"))
|
||||
assertTrue(runCatching { StoreMaintenance.enqueue(app, game, proposal) }.isFailure)
|
||||
assertNull(StoreMaintenance.readOperation(folder))
|
||||
|
||||
StoresState.uninstalling.remove(game.key)
|
||||
folder.deleteRecursively()
|
||||
assertTrue(runCatching { StoreMaintenance.enqueue(app, game, proposal) }.isFailure)
|
||||
assertFalse("stale proposals must not recreate an uninstalled game folder", folder.exists())
|
||||
}
|
||||
|
||||
@Test fun queuedMaintenanceBlocksUninstallAdmission() {
|
||||
val folder = temporary.newFolder().canonicalFile
|
||||
val sidecar = StoreGameSidecar(Store.EPIC, "maintenance-before-uninstall", "Example", "bin/game.exe")
|
||||
sidecar.write(folder)
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
StoreMaintenance.register(adapter)
|
||||
StoreMaintenance.enqueue(RuntimeEnvironment.getApplication(), game,
|
||||
MaintenanceProposal(folder, sidecar, "target", MaintenanceAction.UPDATE, target = JSONObject().put("schema", 1)))
|
||||
|
||||
assertFalse(StoreMaintenance.beginUninstall(game))
|
||||
assertFalse(game.key in StoresState.uninstalling)
|
||||
assertEquals("queued", StoreMaintenance.readOperation(folder)!!.getString("phase"))
|
||||
}
|
||||
|
||||
@Test fun inFlightMaintenancePreparationBlocksUninstallAdmission() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val folder = temporary.newFolder().canonicalFile
|
||||
val sidecar = StoreGameSidecar(Store.EPIC, "prepare-uninstall-race", "Example", "bin/game.exe")
|
||||
sidecar.write(folder)
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
val proposal = MaintenanceProposal(folder, sidecar, "target", MaintenanceAction.UPDATE,
|
||||
target = JSONObject().put("schema", 1))
|
||||
val enteredPrepare = CountDownLatch(1)
|
||||
val finishPrepare = CountDownLatch(1)
|
||||
val failure = AtomicReference<Throwable?>()
|
||||
StoreMaintenance.register(object : StoreMaintenanceAdapter {
|
||||
override val store = Store.EPIC
|
||||
override fun capabilities(game: InstalledStoreGame) = setOf(MaintenanceAction.UPDATE)
|
||||
override fun check(context: Context, game: InstalledStoreGame) = MaintenanceCheck()
|
||||
override fun prepare(context: Context, game: InstalledStoreGame, action: MaintenanceAction): MaintenanceProposal {
|
||||
enteredPrepare.countDown()
|
||||
check(finishPrepare.await(5, TimeUnit.SECONDS))
|
||||
return proposal
|
||||
}
|
||||
override fun enqueue(context: Context, game: InstalledStoreGame, proposal: MaintenanceProposal) = true
|
||||
override fun resume(context: Context, game: InstalledStoreGame, operation: JSONObject) = Unit
|
||||
})
|
||||
val worker = Thread({ runCatching { StoreMaintenance.prepare(app, game, MaintenanceAction.UPDATE) }
|
||||
.onFailure(failure::set) }, "test-maintenance-prepare")
|
||||
worker.start()
|
||||
|
||||
assertTrue(enteredPrepare.await(5, TimeUnit.SECONDS))
|
||||
try {
|
||||
assertFalse(StoreMaintenance.beginUninstall(game))
|
||||
assertFalse(game.key in StoresState.uninstalling)
|
||||
} finally {
|
||||
finishPrepare.countDown()
|
||||
}
|
||||
worker.join(TimeUnit.SECONDS.toMillis(5))
|
||||
assertFalse("maintenance preparation should finish", worker.isAlive)
|
||||
assertNull(failure.get())
|
||||
assertTrue(StoreMaintenance.beginUninstall(game))
|
||||
StoresState.uninstalling.remove(game.key)
|
||||
}
|
||||
|
||||
@Test fun applyLeaseIsExclusiveAndMarksTheJournalBeforeMutation() {
|
||||
val folder = temporary.newFolder().canonicalFile
|
||||
val sidecar = StoreGameSidecar(Store.EPIC, "app", "Example", "bin/game.exe")
|
||||
sidecar.write(folder)
|
||||
val game = InstalledStoreGame(sidecar, folder)
|
||||
StoreMaintenance.register(adapter)
|
||||
StoreMaintenance.enqueue(RuntimeEnvironment.getApplication(), game,
|
||||
MaintenanceProposal(folder, sidecar, "version 2", MaintenanceAction.UPDATE, target = JSONObject().put("schema", 1)))
|
||||
|
||||
val lease = StoreMaintenance.beginApplyLease(game)
|
||||
try {
|
||||
assertEquals("applying", StoreMaintenance.readOperation(folder)!!.getString("phase"))
|
||||
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(folder)!!.state)
|
||||
assertTrue(runCatching { StoreMaintenance.beginApplyLease(game) }.isFailure)
|
||||
} finally {
|
||||
lease.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun unsupportedOrMismatchedJournalBlocksLaunch() {
|
||||
val folder = temporary.newFolder().canonicalFile
|
||||
val game = InstalledStoreGame(StoreGameSidecar(Store.EPIC, "app", "Example", "bin/game.exe"), folder)
|
||||
File(folder, ".droiddeck-maintenance").mkdirs()
|
||||
StoreMaintenance.operationFile(folder).writeText(JSONObject().put("schema", 9).put("folder", folder.path).put("phase", "download").toString())
|
||||
|
||||
assertTrue(StoreMaintenance.launchExcluded(game))
|
||||
assertTrue(runCatching { StoreMaintenance.readOperation(folder) }.isFailure)
|
||||
assertEquals(RecoveryState.NEEDS_ATTENTION, StoreMaintenance.recovery(RuntimeEnvironment.getApplication(), game).state)
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import com.droiddeck.launcher.stores.maintenance.StoreMaintenance
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Test
|
||||
|
||||
class XboxMaintenancePersistenceTest {
|
||||
@Test fun completedMaintenanceDoesNotPersistQueueMarkers() {
|
||||
val persisted = XboxInstaller.maintenanceSidecarExtra(
|
||||
mapOf(
|
||||
"contentId" to "old-content",
|
||||
"market" to "US",
|
||||
"preferredLanguage" to "fr-FR",
|
||||
StoreMaintenance.OPERATION_KEY to "UPDATE",
|
||||
StoreMaintenance.FOLDER_KEY to "/games/example",
|
||||
),
|
||||
"new-content",
|
||||
"GB",
|
||||
)
|
||||
|
||||
assertEquals("new-content", persisted["contentId"])
|
||||
assertEquals("GB", persisted["market"])
|
||||
assertEquals("fr-FR", persisted["preferredLanguage"])
|
||||
assertFalse(persisted.containsKey(StoreMaintenance.OPERATION_KEY))
|
||||
assertFalse(persisted.containsKey(StoreMaintenance.FOLDER_KEY))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
Generation 1 fixtures from GOG's public Rayman 2 repository, timestamp 31847977,
|
||||
retrieved 2026-10-28. The repository and Neutral depot are complete. The English
|
||||
depot is an excerpt containing its first three original file entries.
|
||||
|
||||
https://gog-cdn-fastly.gog.com/content-system/v1/manifests/1207658940/windows/31847977/repository.json
|
||||
|
||||
The fixtures retain provider paths, support flags, range offsets, and original
|
||||
hexadecimal hashes. They contain no game payload, credentials, or signed links.
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"version": 1,
|
||||
"depot": {
|
||||
"name": "Rayman 2 - The Great Escape",
|
||||
"files": [
|
||||
{
|
||||
"offset": 384206096,
|
||||
"hash": "a08070ecde7f746779259f7ce5775747",
|
||||
"url": "1207658940/main.bin",
|
||||
"path": "/Data/World/Levels/Raycap/Raycap.snd",
|
||||
"size": 32
|
||||
},
|
||||
{
|
||||
"offset": 114255832,
|
||||
"hash": "67165fe729ffda351a04e8bd92e05531",
|
||||
"url": "1207658940/main.bin",
|
||||
"path": "/Data/World/Sound/Bnk_29.bnm",
|
||||
"size": 76
|
||||
},
|
||||
{
|
||||
"offset": 97474601,
|
||||
"hash": "2d2e0b308cae5ff44a620fd32bf6cb4d",
|
||||
"url": "1207658940/main.bin",
|
||||
"path": "/Data/World/Sound/Bnk_43.bnm",
|
||||
"size": 76
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"version": 1,
|
||||
"depot": {
|
||||
"name": "Rayman 2 - The Great Escape",
|
||||
"files": [
|
||||
{
|
||||
"offset": 0,
|
||||
"path": "1207658940/galaxy_rayman2_2.1.0.39.exe",
|
||||
"size": 1258944,
|
||||
"support": true,
|
||||
"hash": "ee2c247373733f29782395f1f92622f6",
|
||||
"url": "1207658940/main.bin"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user