Integrate persistent updater metadata and failure operations
This commit is contained in:
commit
9bbb4bab25
15 changed files with 559 additions and 99 deletions
|
|
@ -38,6 +38,7 @@ class HouseholdUpdateControllerTest {
|
|||
private var truncated = false
|
||||
private var chunked = false
|
||||
private var unsupported = false
|
||||
private var manifestSigner = UpdateChannel.SIGNER
|
||||
private var redirect = false
|
||||
private var redirectTarget: String? = null
|
||||
private val requests = mutableListOf<Map<String, List<String>>>()
|
||||
|
|
@ -49,12 +50,14 @@ class HouseholdUpdateControllerTest {
|
|||
var permission = true
|
||||
var settingsAvailable = true
|
||||
var installs = 0
|
||||
var settingsOpens = 0
|
||||
var inspectAction: (() -> Unit)? = null
|
||||
var outcome = InstallOutcome.Cancelled
|
||||
override fun installed() = installed
|
||||
override fun inspect(file: File) = archive
|
||||
override fun inspect(file: File): ApkIdentity { inspectAction?.invoke(); return archive }
|
||||
override fun hasInstallPermission() = permission
|
||||
override fun openPermissionSettings() = settingsAvailable
|
||||
override fun install(file: File, outcome: (InstallOutcome) -> Unit) { installs++; outcome(this.outcome) }
|
||||
override fun openPermissionSettings(): Boolean { settingsOpens++; return settingsAvailable }
|
||||
override fun install(file: File, asset: UpdateAsset, outcome: (InstallOutcome) -> Unit) { installs++; outcome(this.outcome) }
|
||||
}
|
||||
private val preferences = object : UpdatePreferences {
|
||||
override val autoCheck = MutableStateFlow(true)
|
||||
|
|
@ -104,7 +107,7 @@ class HouseholdUpdateControllerTest {
|
|||
@After fun stop() { server.stop(0) }
|
||||
|
||||
private fun manifest() = UpdateManifest(1, UpdateChannel.PACKAGE, "1.1.1", code,
|
||||
"2026-11-07T12:00:00Z", "a".repeat(40), "pwolfskin-opt-v1.1.1", UpdateChannel.SIGNER,
|
||||
"2026-11-07T12:00:00Z", "a".repeat(40), "pwolfskin-opt-v1.1.1", manifestSigner,
|
||||
listOf(UpdateAsset(if (unsupported) "x86_64" else "armeabi-v7a", if (unsupported) "Wolfskin-x86_64.apk" else "Wolfskin-armeabi-v7a.apk", apk.size.toLong(),
|
||||
if (badHash) "0".repeat(64) else MessageDigest.getInstance("SHA-256").digest(apk).joinToString("") { "%02x".format(it) }, 23)))
|
||||
|
||||
|
|
@ -115,17 +118,32 @@ class HouseholdUpdateControllerTest {
|
|||
val controller = controller(this)
|
||||
controller.check(true); advanceUntilIdle()
|
||||
assertTrue(controller.state.value is UpdateUiState.Available)
|
||||
val metadata = controller.release.value
|
||||
assertEquals(controller.state.value, metadata)
|
||||
controller.download(); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.Ready("1.1.1"), controller.state.value)
|
||||
assertEquals(metadata, controller.release.value)
|
||||
assertEquals(0, platform.installs)
|
||||
val restored = controller(this); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.Ready("1.1.1"), restored.state.value)
|
||||
assertEquals(metadata, restored.release.value)
|
||||
restored.install(); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.InstallCancelled, restored.state.value)
|
||||
assertEquals(1, platform.installs)
|
||||
assertTrue(File(directory, "verified.apk").exists())
|
||||
}
|
||||
|
||||
@Test fun existingManifestOnlyReadyRecordRemainsReadable() = runTest {
|
||||
val old = controller(this); old.check(true); advanceUntilIdle(); old.download(); advanceUntilIdle()
|
||||
val metadata = old.release.value!!
|
||||
assertEquals(manifest(), UpdateManifest.parse(File(directory, "ready.json").readText()))
|
||||
File(directory, "ready.json").writeText(UpdateManifest.encode(manifest()))
|
||||
val recreated = controller(this); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.Ready("1.1.1"), recreated.state.value)
|
||||
assertEquals(metadata.copy(notes = ""), recreated.release.value)
|
||||
assertEquals(0, platform.installs)
|
||||
}
|
||||
|
||||
@Test fun equalCodeIsUpToDateAndOlderCodeIsNotASuccess() = runTest {
|
||||
code = 65
|
||||
val equal = controller(this); equal.check(true); advanceUntilIdle()
|
||||
|
|
@ -163,6 +181,15 @@ class HouseholdUpdateControllerTest {
|
|||
assertEquals(UpdateFailure.UnsupportedAbi, (unsupported.state.value as UpdateUiState.Failed).kind)
|
||||
}
|
||||
|
||||
@Test fun manifestSignerDifferentFromInstallationFailsBeforeDownload() = runTest {
|
||||
manifestSigner = "b".repeat(64)
|
||||
val controller = controller(this)
|
||||
controller.check(true); advanceUntilIdle()
|
||||
assertEquals(UpdateFailure.WrongSigner, (controller.state.value as UpdateUiState.Failed).kind)
|
||||
assertFalse(File(directory, "verified.apk").exists())
|
||||
assertEquals(0, platform.installs)
|
||||
}
|
||||
|
||||
@Test fun checksumAndLengthFailuresNeverCommitReady() = runTest {
|
||||
for (badChecksum in listOf(true, false)) {
|
||||
badHash = badChecksum; truncated = !badChecksum
|
||||
|
|
@ -243,6 +270,53 @@ class HouseholdUpdateControllerTest {
|
|||
assertEquals(UpdateUiState.NoInstaller, controller.state.value)
|
||||
}
|
||||
|
||||
@Test fun permissionDismissalRetainsReadyAndInstallReopensSettings() = runTest {
|
||||
val controller = controller(this); controller.check(true); advanceUntilIdle(); controller.download(); advanceUntilIdle()
|
||||
val metadata = controller.release.value
|
||||
platform.permission = false
|
||||
controller.install(); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.PermissionNeeded, controller.state.value)
|
||||
controller.install(); advanceUntilIdle()
|
||||
assertEquals(2, platform.settingsOpens)
|
||||
controller.cancel(); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.Ready("1.1.1"), controller.state.value)
|
||||
assertEquals(metadata, controller.release.value)
|
||||
assertArrayEquals(apk, File(directory, "verified.apk").readBytes())
|
||||
controller.install(); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.PermissionNeeded, controller.state.value)
|
||||
assertEquals(3, platform.settingsOpens)
|
||||
assertEquals(0, platform.installs)
|
||||
}
|
||||
|
||||
@Test fun handoffDismissalKeepsReadyWithoutAllowingAnotherOwnedSession() = runTest {
|
||||
val controller = controller(this); controller.check(true); advanceUntilIdle(); controller.download(); advanceUntilIdle()
|
||||
platform.outcome = InstallOutcome.Pending
|
||||
controller.install(); advanceUntilIdle()
|
||||
controller.cancel(); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.Ready("1.1.1"), controller.state.value)
|
||||
controller.handleInstallOutcome(InstallOutcome.Pending); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.Ready("1.1.1"), controller.state.value)
|
||||
val before = requests.size
|
||||
controller.install(); advanceUntilIdle()
|
||||
controller.check(true); advanceUntilIdle()
|
||||
controller.download(); advanceUntilIdle()
|
||||
assertEquals(1, platform.installs)
|
||||
assertEquals(before, requests.size)
|
||||
assertArrayEquals(apk, File(directory, "verified.apk").readBytes())
|
||||
controller.handleInstallOutcome(InstallOutcome.Cancelled); advanceUntilIdle()
|
||||
controller.install(); advanceUntilIdle()
|
||||
assertEquals(2, platform.installs)
|
||||
}
|
||||
|
||||
@Test fun dismissalDuringInstallVerificationDoesNotDiscardVerifiedBytes() = runTest {
|
||||
val controller = controller(this); controller.check(true); advanceUntilIdle(); controller.download(); advanceUntilIdle()
|
||||
platform.inspectAction = { controller.cancel() }
|
||||
controller.install(); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.Ready("1.1.1"), controller.state.value)
|
||||
assertArrayEquals(apk, File(directory, "verified.apk").readBytes())
|
||||
assertEquals(0, platform.installs)
|
||||
}
|
||||
|
||||
@Test fun corruptPersistedBytesAndUnverifiedPartialsAreDiscarded() = runTest {
|
||||
val controller = controller(this); controller.check(true); advanceUntilIdle(); controller.download(); advanceUntilIdle()
|
||||
File(directory, "verified.apk").appendText("corrupt")
|
||||
|
|
@ -263,6 +337,26 @@ class HouseholdUpdateControllerTest {
|
|||
assertEquals(UpdateUiState.Ready("1.1.1"), controller.state.value)
|
||||
}
|
||||
|
||||
@Test fun failuresIdentifyCheckDownloadAndInstallWithoutParsingMessages() = runTest {
|
||||
val controller = controller(this)
|
||||
releaseStatus = 403
|
||||
controller.check(true); advanceUntilIdle()
|
||||
assertEquals(UpdateOperation.Check, (controller.state.value as UpdateUiState.Failed).operation)
|
||||
releaseStatus = 200
|
||||
controller.retry(); advanceUntilIdle()
|
||||
assetStatus = 403
|
||||
controller.download(); advanceUntilIdle()
|
||||
assertEquals(UpdateOperation.Download, (controller.state.value as UpdateUiState.Failed).operation)
|
||||
assetStatus = 200
|
||||
controller.retry(); advanceUntilIdle()
|
||||
File(directory, "verified.apk").writeBytes(ByteArray(apk.size))
|
||||
controller.install(); advanceUntilIdle()
|
||||
val failed = controller.state.value as UpdateUiState.Failed
|
||||
assertEquals(UpdateOperation.Install, failed.operation)
|
||||
assertEquals(UpdateFailure.ChecksumMismatch, failed.kind)
|
||||
assertFalse(File(directory, "ready.json").exists())
|
||||
}
|
||||
|
||||
@Test fun interruptedWireDownloadDoesNotPersistReady() = runTest {
|
||||
truncated = true; wireTruncated = true
|
||||
val controller = controller(this); controller.check(true); advanceUntilIdle()
|
||||
|
|
@ -289,6 +383,8 @@ class HouseholdUpdateControllerTest {
|
|||
controller.install(); advanceUntilIdle()
|
||||
assertEquals(65L, controller.installedVersion.value.versionCode)
|
||||
assertTrue(File(directory, "verified.apk").exists())
|
||||
controller.cancel(); advanceUntilIdle(); controller.install(); advanceUntilIdle()
|
||||
assertEquals(1, platform.installs)
|
||||
platform.installed = platform.archive
|
||||
controller.onResume(); advanceUntilIdle()
|
||||
assertEquals(100001L, controller.installedVersion.value.versionCode)
|
||||
|
|
@ -306,6 +402,8 @@ class HouseholdUpdateControllerTest {
|
|||
replaced.handleInstallOutcome(InstallOutcome.Cancelled); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.Idle, replaced.state.value)
|
||||
assertFalse(File(directory, "verified.apk").exists())
|
||||
replaced.check(true); advanceUntilIdle()
|
||||
assertEquals(UpdateUiState.UpToDate, replaced.state.value)
|
||||
}
|
||||
|
||||
@Test fun reentryCheckCannotReplacePendingConfirmationOrStartAnotherSession() = runTest {
|
||||
|
|
|
|||
|
|
@ -21,19 +21,26 @@ class UpdateBehaviorTest {
|
|||
UpdateUiState.InstallCancelled to listOf(UpdateCommand.Install, UpdateCommand.Notes),
|
||||
UpdateUiState.Offline to listOf(UpdateCommand.Retry),
|
||||
UpdateUiState.NoInstaller to listOf(UpdateCommand.Retry, UpdateCommand.Classic),
|
||||
) + UpdateFailure.entries.map { UpdateUiState.Failed(it, "operation failed") to listOf(UpdateCommand.Retry, UpdateCommand.Back) }
|
||||
) + UpdateFailure.entries.map { UpdateUiState.Failed(it, "operation failed", UpdateOperation.Download) to listOf(UpdateCommand.Retry, UpdateCommand.Back) }
|
||||
expected.forEach { (state, commands) ->
|
||||
assertEquals(state.toString(), commands, presentUpdate(state, updateReleaseFixture()).actions.map { it.command })
|
||||
}
|
||||
assertNotEquals(presentUpdate(UpdateUiState.UpToDate, null), presentUpdate(UpdateUiState.NoReleasePublished, null))
|
||||
}
|
||||
|
||||
@Test fun refreshedInstalledIdentityDoesNotRequireOrMaskAChannelCheck() {
|
||||
val installed = "1.1.1"
|
||||
val refreshed = presentUpdate(UpdateUiState.Idle, null, installed)
|
||||
assertNotEquals(presentUpdate(UpdateUiState.Idle, null), refreshed)
|
||||
assertEquals(listOf(UpdateCommand.Check), refreshed.actions.map { it.command })
|
||||
assertEquals(presentUpdate(UpdateUiState.Checking, null),
|
||||
presentUpdate(UpdateUiState.Checking, null, installed))
|
||||
}
|
||||
|
||||
@Test fun percentageRequiresPositiveTotalAndIsBounded() {
|
||||
listOf(null, 0L, -1L).forEach { total ->
|
||||
val ui = presentUpdate(UpdateUiState.Downloading(20_100_000, total), updateReleaseFixture())
|
||||
assertNull(ui.fraction)
|
||||
assertTrue(ui.title.isEmpty())
|
||||
assertNotNull(ui.byteProgress)
|
||||
}
|
||||
assertEquals(.42f, presentUpdate(UpdateUiState.Downloading(20_076_000, 47_800_000), null).fraction!!, .0001f)
|
||||
assertEquals(1f, presentUpdate(UpdateUiState.Downloading(90, 30), null).fraction!!, 0f)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,34 @@
|
|||
// SPDX-License-Identifier: GPL-2.0-only
|
||||
package org.justinvisser.wolfskin.tv.update
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.security.MessageDigest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Test
|
||||
|
||||
/** A replacement or incomplete stream must never reach the session commit boundary. */
|
||||
class UpdateSessionStreamTest {
|
||||
private val original = ByteArray(128 * 1024) { (it % 251).toByte() }
|
||||
private val asset = UpdateAsset("armeabi-v7a", "Wolfskin-armeabi-v7a.apk", original.size.toLong(),
|
||||
MessageDigest.getInstance("SHA-256").digest(original).toHexString(), 23)
|
||||
|
||||
@Test fun sameLengthReplacementAfterVerificationIsRejected() {
|
||||
val replaced = original.copyOf().also { it[it.lastIndex] = (it.last() + 1).toByte() }
|
||||
expectMismatch(replaced)
|
||||
}
|
||||
|
||||
@Test fun truncatedAndOversizedSessionStreamsAreRejected() {
|
||||
expectMismatch(original.copyOf(original.size - 1))
|
||||
expectMismatch(original + byteArrayOf(1))
|
||||
}
|
||||
|
||||
private fun expectMismatch(bytes: ByteArray) {
|
||||
try {
|
||||
bytes.inputStream().use { copyVerifiedUpdate(it, ByteArrayOutputStream(), asset) }
|
||||
fail("Changed installation bytes were accepted")
|
||||
} catch (error: UpdateException) {
|
||||
assertEquals(UpdateFailure.ChecksumMismatch, error.kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -12,6 +12,8 @@ import android.os.Build
|
|||
import android.provider.Settings
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.security.MessageDigest
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
|
@ -47,7 +49,7 @@ class AndroidUpdatePlatform @Inject constructor(@param:ApplicationContext privat
|
|||
return try { context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); true } catch (_: RuntimeException) { false }
|
||||
}
|
||||
|
||||
override fun install(file: File, outcome: (InstallOutcome) -> Unit) {
|
||||
override fun install(file: File, asset: UpdateAsset, outcome: (InstallOutcome) -> Unit) {
|
||||
if (context.noBackupFilesDir.usableSpace < file.length()) {
|
||||
outcome(InstallOutcome.InsufficientStorage)
|
||||
return
|
||||
|
|
@ -55,7 +57,7 @@ class AndroidUpdatePlatform @Inject constructor(@param:ApplicationContext privat
|
|||
val installer = manager.packageInstaller
|
||||
val parameters = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {
|
||||
setAppPackageName(context.packageName)
|
||||
setSize(file.length())
|
||||
setSize(asset.bytes)
|
||||
if (Build.VERSION.SDK_INT >= 31) setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_REQUIRED)
|
||||
}
|
||||
var sessionId: Int? = null
|
||||
|
|
@ -63,8 +65,8 @@ class AndroidUpdatePlatform @Inject constructor(@param:ApplicationContext privat
|
|||
sessionId = installer.createSession(parameters)
|
||||
check(sessions.edit().putInt("id", sessionId).commit())
|
||||
installer.openSession(sessionId).use { session ->
|
||||
session.openWrite("Wolfskin.apk", 0, file.length()).use { output ->
|
||||
file.inputStream().use { it.copyTo(output) }
|
||||
session.openWrite("Wolfskin.apk", 0, asset.bytes).use { output ->
|
||||
file.inputStream().use { copyVerifiedUpdate(it, output, asset) }
|
||||
session.fsync(output)
|
||||
}
|
||||
val intent = Intent(context, UpdateInstallReceiver::class.java).setAction("${context.packageName}.UPDATE_RESULT")
|
||||
|
|
@ -72,8 +74,9 @@ class AndroidUpdatePlatform @Inject constructor(@param:ApplicationContext privat
|
|||
val result = PendingIntent.getBroadcast(context, sessionId, intent, flags)
|
||||
session.commit(result.intentSender)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
} catch (error: Exception) {
|
||||
sessionId?.let { runCatching { installer.abandonSession(it) } }
|
||||
if (error is UpdateException) throw error
|
||||
outcome(InstallOutcome.Unavailable)
|
||||
}
|
||||
}
|
||||
|
|
@ -88,3 +91,21 @@ class AndroidUpdatePlatform @Inject constructor(@param:ApplicationContext privat
|
|||
} catch (_: RuntimeException) { false }
|
||||
}
|
||||
}
|
||||
|
||||
/** Check the bytes actually staged into Android, not a prior read of the private path. */
|
||||
internal fun copyVerifiedUpdate(input: InputStream, output: OutputStream, asset: UpdateAsset) {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var count = 0L
|
||||
while (true) {
|
||||
val length = input.read(buffer)
|
||||
if (length < 0) break
|
||||
count += length
|
||||
if (count > asset.bytes) throw UpdateException(UpdateFailure.ChecksumMismatch, "APK changed while staging installation")
|
||||
digest.update(buffer, 0, length)
|
||||
output.write(buffer, 0, length)
|
||||
}
|
||||
if (count != asset.bytes || digest.digest().toHexString() != asset.sha256) {
|
||||
throw UpdateException(UpdateFailure.ChecksumMismatch, "APK changed while staging installation")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,26 +40,32 @@ class HouseholdUpdateController(
|
|||
) : UpdateController {
|
||||
private val mutableState = MutableStateFlow<UpdateUiState>(UpdateUiState.Idle)
|
||||
private val mutableVersion = MutableStateFlow(platform.installed().version)
|
||||
private val mutableRelease = MutableStateFlow<UpdateUiState.Available?>(null)
|
||||
override val state = mutableState.asStateFlow()
|
||||
override val installedVersion = mutableVersion.asStateFlow()
|
||||
override val autoCheck = preferences.autoCheck
|
||||
override val release = mutableRelease.asStateFlow()
|
||||
private var candidate: UpdateCandidate? = null
|
||||
private var ready: UpdateManifest? = null
|
||||
private var operation: Job? = null
|
||||
@Volatile private var installerActive = false
|
||||
private var retryOperation: () -> Unit = { check(true) }
|
||||
private val restored = scope.async {
|
||||
ready = store.restore(abis, sdk)
|
||||
ready?.let { mutableState.value = UpdateUiState.Ready(it.versionName) }
|
||||
store.restore(abis, sdk)?.let {
|
||||
ready = it.manifest
|
||||
mutableRelease.value = available(it.manifest, it.asset, it.notes)
|
||||
mutableState.value = UpdateUiState.Ready(it.manifest.versionName)
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun runOperation(action: suspend () -> Unit): Unit {
|
||||
private fun runOperation(operationKind: UpdateOperation, action: suspend () -> Unit): Unit {
|
||||
if (operation?.isActive == true) return
|
||||
operation = scope.launch {
|
||||
restored.await()
|
||||
try { action() }
|
||||
catch (error: CancellationException) { throw error }
|
||||
catch (error: UpdateException) { mutableState.value = UpdateUiState.Failed(error.kind, error.message) }
|
||||
catch (error: UpdateException) { mutableState.value = UpdateUiState.Failed(error.kind, error.message, operationKind) }
|
||||
catch (_: UnknownHostException) { mutableState.value = UpdateUiState.Offline }
|
||||
catch (_: ConnectException) { mutableState.value = UpdateUiState.Offline }
|
||||
catch (error: IOException) {
|
||||
|
|
@ -67,16 +73,16 @@ class HouseholdUpdateController(
|
|||
val full = state.value is UpdateUiState.Downloading && release != null &&
|
||||
store.directory.usableSpace < release.asset.bytes
|
||||
mutableState.value = UpdateUiState.Failed(if (full) UpdateFailure.InsufficientStorage else UpdateFailure.Network,
|
||||
if (full) "Not enough storage for the update" else "Update transfer failed; try again")
|
||||
if (full) "Not enough storage for the update" else "Update transfer failed; try again", operationKind)
|
||||
}
|
||||
catch (_: Exception) { mutableState.value = UpdateUiState.Failed(UpdateFailure.InvalidMetadata, "Update could not be processed") }
|
||||
catch (_: Exception) { mutableState.value = UpdateUiState.Failed(UpdateFailure.InvalidMetadata, "Update could not be processed", operationKind) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun systemOwnsFlow(current: UpdateUiState): Boolean =
|
||||
current == UpdateUiState.HandingOff || current == UpdateUiState.PermissionNeeded
|
||||
installerActive || current == UpdateUiState.HandingOff || current == UpdateUiState.PermissionNeeded
|
||||
|
||||
override fun check(manual: Boolean): Unit = runOperation {
|
||||
override fun check(manual: Boolean): Unit = runOperation(UpdateOperation.Check) {
|
||||
if (systemOwnsFlow(state.value)) return@runOperation
|
||||
if (!manual && !preferences.enabled()) return@runOperation
|
||||
ready?.let { manifest ->
|
||||
|
|
@ -86,25 +92,34 @@ class HouseholdUpdateController(
|
|||
retryOperation = { check(true) }
|
||||
mutableState.value = UpdateUiState.Checking
|
||||
val release = transport.latest(preferences.url(), abis, sdk)
|
||||
if (release == null) { mutableState.value = UpdateUiState.NoReleasePublished; return@runOperation }
|
||||
if (release == null) {
|
||||
candidate = null; mutableRelease.value = null
|
||||
mutableState.value = UpdateUiState.NoReleasePublished
|
||||
return@runOperation
|
||||
}
|
||||
val installed = platform.installed()
|
||||
mutableVersion.value = installed.version
|
||||
if (release.manifest.packageId != installed.packageId) throw UpdateException(UpdateFailure.WrongPackage, "Release belongs to a different application")
|
||||
if (installed.signers != setOf(release.manifest.signerSha256)) throw UpdateException(UpdateFailure.WrongSigner, "Release signer differs from this installation")
|
||||
if (release.manifest.versionCode < installed.version.versionCode) throw UpdateException(UpdateFailure.LowerVersionCode, "Channel release is older than this installation")
|
||||
if (release.manifest.versionCode == installed.version.versionCode) {
|
||||
candidate = null
|
||||
candidate = null; mutableRelease.value = null
|
||||
mutableState.value = UpdateUiState.UpToDate
|
||||
} else { candidate = release; mutableState.value = available(release) }
|
||||
} else {
|
||||
candidate = release
|
||||
val metadata = available(release.manifest, release.asset, release.notes)
|
||||
mutableRelease.value = metadata
|
||||
mutableState.value = metadata
|
||||
}
|
||||
}
|
||||
|
||||
private fun available(release: UpdateCandidate): UpdateUiState.Available {
|
||||
private fun available(manifest: UpdateManifest, asset: UpdateAsset, notes: String): UpdateUiState.Available {
|
||||
val date = DateTimeFormatter.ofLocalizedDate(java.time.format.FormatStyle.MEDIUM).withLocale(Locale.getDefault())
|
||||
.withZone(ZoneId.systemDefault()).format(Instant.parse(release.manifest.publishedAt))
|
||||
return UpdateUiState.Available(release.manifest.versionName, release.asset.bytes, date, release.notes)
|
||||
.withZone(ZoneId.systemDefault()).format(Instant.parse(manifest.publishedAt))
|
||||
return UpdateUiState.Available(manifest.versionName, asset.bytes, date, notes)
|
||||
}
|
||||
|
||||
override fun download(): Unit = runOperation {
|
||||
override fun download(): Unit = runOperation(UpdateOperation.Download) {
|
||||
if (systemOwnsFlow(state.value)) return@runOperation
|
||||
if (ready != null) return@runOperation
|
||||
val release = candidate ?: return@runOperation
|
||||
|
|
@ -115,7 +130,7 @@ class HouseholdUpdateController(
|
|||
try {
|
||||
transport.download(release, store.partial) { done, total -> mutableState.value = UpdateUiState.Downloading(done, total) }
|
||||
currentCoroutineContext().ensureActive()
|
||||
store.commit(release.manifest, release.asset)
|
||||
store.commit(release.manifest, release.asset, release.notes)
|
||||
currentCoroutineContext().ensureActive()
|
||||
ready = release.manifest
|
||||
mutableState.value = UpdateUiState.Ready(release.manifest.versionName)
|
||||
|
|
@ -127,50 +142,60 @@ class HouseholdUpdateController(
|
|||
|
||||
@Synchronized
|
||||
override fun cancel() {
|
||||
if (systemOwnsFlow(state.value)) return
|
||||
transport.cancel()
|
||||
val previous = operation
|
||||
previous?.cancel()
|
||||
if (!installerActive) previous?.cancel()
|
||||
operation = scope.launch {
|
||||
previous?.join()
|
||||
store.partial.delete()
|
||||
mutableState.value = ready?.let { UpdateUiState.Ready(it.versionName) }
|
||||
?: candidate?.let { available(it) } ?: UpdateUiState.Idle
|
||||
?: candidate?.let { mutableRelease.value } ?: UpdateUiState.Idle
|
||||
}
|
||||
}
|
||||
|
||||
override fun install(): Unit = runOperation {
|
||||
if (state.value == UpdateUiState.HandingOff) return@runOperation
|
||||
override fun install(): Unit = runOperation(UpdateOperation.Install) {
|
||||
if (installerActive || state.value == UpdateUiState.HandingOff) return@runOperation
|
||||
val manifest = ready ?: return@runOperation
|
||||
retryOperation = { install() }
|
||||
try { store.verify(store.apk, manifest, manifest.selectAsset(abis, sdk)) } catch (error: Exception) {
|
||||
val asset = manifest.selectAsset(abis, sdk)
|
||||
try {
|
||||
store.verify(store.apk, manifest, asset)
|
||||
if (!platform.hasInstallPermission()) {
|
||||
mutableState.value = if (platform.openPermissionSettings()) UpdateUiState.PermissionNeeded else UpdateUiState.NoInstaller
|
||||
return@runOperation
|
||||
}
|
||||
currentCoroutineContext().ensureActive()
|
||||
installerActive = true
|
||||
mutableState.value = UpdateUiState.HandingOff
|
||||
platform.install(store.apk, asset, ::handleInstallOutcome)
|
||||
} catch (error: CancellationException) {
|
||||
installerActive = false
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
installerActive = false
|
||||
store.clear(); ready = null
|
||||
retryOperation = { if (candidate != null) download() else check(true) }
|
||||
throw error
|
||||
}
|
||||
if (!platform.hasInstallPermission()) {
|
||||
mutableState.value = if (platform.openPermissionSettings()) UpdateUiState.PermissionNeeded else UpdateUiState.NoInstaller
|
||||
return@runOperation
|
||||
}
|
||||
mutableState.value = UpdateUiState.HandingOff
|
||||
platform.install(store.apk, ::handleInstallOutcome)
|
||||
}
|
||||
|
||||
fun handleInstallOutcome(outcome: InstallOutcome) {
|
||||
scope.launch {
|
||||
restored.await()
|
||||
installerActive = outcome == InstallOutcome.Pending || outcome == InstallOutcome.Success
|
||||
if (ready == null && outcome != InstallOutcome.Pending) {
|
||||
installerActive = false
|
||||
retryOperation = { check(true) }
|
||||
mutableState.value = UpdateUiState.Idle
|
||||
onResume()
|
||||
return@launch
|
||||
}
|
||||
mutableState.value = when (outcome) {
|
||||
InstallOutcome.Pending -> UpdateUiState.HandingOff
|
||||
InstallOutcome.Pending -> if (state.value is UpdateUiState.Ready) state.value else UpdateUiState.HandingOff
|
||||
InstallOutcome.Cancelled -> UpdateUiState.InstallCancelled
|
||||
InstallOutcome.Unavailable -> UpdateUiState.NoInstaller
|
||||
InstallOutcome.InsufficientStorage -> UpdateUiState.Failed(UpdateFailure.InsufficientStorage, "Android needs more storage to install the retained update")
|
||||
InstallOutcome.Failed -> UpdateUiState.Failed(UpdateFailure.InvalidMetadata, "Android could not install the update; the verified download is retained")
|
||||
InstallOutcome.InsufficientStorage -> UpdateUiState.Failed(UpdateFailure.InsufficientStorage, "Android needs more storage to install the retained update", UpdateOperation.Install)
|
||||
InstallOutcome.Failed -> UpdateUiState.Failed(UpdateFailure.InvalidMetadata, "Android could not install the update; the verified download is retained", UpdateOperation.Install)
|
||||
InstallOutcome.Success -> UpdateUiState.HandingOff
|
||||
}
|
||||
if (outcome != InstallOutcome.Pending) onResume()
|
||||
|
|
@ -186,7 +211,8 @@ class HouseholdUpdateController(
|
|||
mutableVersion.value = platform.installed().version
|
||||
val manifest = ready ?: return@launch
|
||||
if (mutableVersion.value.versionCode >= manifest.versionCode) {
|
||||
store.clear(); ready = null; candidate = null; mutableState.value = UpdateUiState.Idle
|
||||
installerActive = false
|
||||
store.clear(); ready = null; candidate = null; mutableRelease.value = null; mutableState.value = UpdateUiState.Idle
|
||||
} else if (state.value == UpdateUiState.PermissionNeeded) {
|
||||
// Returning from settings requires another explicit Install press.
|
||||
mutableState.value = if (platform.hasInstallPermission()) UpdateUiState.Ready(manifest.versionName)
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ interface UpdateController {
|
|||
|
||||
fun check(manual: Boolean)
|
||||
fun download()
|
||||
/** Cancel partial bytes, or dismiss permission/handoff while retaining a verified APK. */
|
||||
/** Discard partial bytes; retain verified bytes and restore Ready without duplicating a system session. */
|
||||
fun cancel()
|
||||
fun install()
|
||||
fun retry()
|
||||
|
|
@ -38,11 +38,14 @@ sealed interface UpdateUiState {
|
|||
data object PermissionNeeded : UpdateUiState
|
||||
data object HandingOff : UpdateUiState
|
||||
data object InstallCancelled : UpdateUiState
|
||||
data class Failed(val kind: UpdateFailure, val message: String) : UpdateUiState
|
||||
data class Failed(val kind: UpdateFailure, val message: String, val operation: UpdateOperation) : UpdateUiState
|
||||
data object Offline : UpdateUiState
|
||||
data object NoInstaller : UpdateUiState
|
||||
}
|
||||
|
||||
/** The failed action is structured; UI must not infer it from a reason string. */
|
||||
enum class UpdateOperation { Check, Download, Install }
|
||||
|
||||
/** Failures are distinct from a successful version comparison or an empty channel. */
|
||||
enum class UpdateFailure {
|
||||
Network, HttpRefused, InvalidMetadata, UnsupportedAbi, InsufficientStorage,
|
||||
|
|
|
|||
|
|
@ -38,13 +38,12 @@ fun presentUpdate(state: UpdateUiState, release: UpdateUiState.Available?, updat
|
|||
val retry = UpdateAction("Retry", UpdateCommand.Retry, true)
|
||||
val metadata = updateMetadata(release)
|
||||
return when (state) {
|
||||
UpdateUiState.Idle -> UpdatePresentation(actions = listOf(UpdateAction("Check for updates", UpdateCommand.Check, true)))
|
||||
UpdateUiState.Idle -> updatedVersion?.let(::updatedPresentation)
|
||||
?: UpdatePresentation(actions = listOf(UpdateAction("Check for updates", UpdateCommand.Check, true)))
|
||||
UpdateUiState.Checking -> UpdatePresentation(actions = listOf(back), progress = true)
|
||||
UpdateUiState.UpToDate -> UpdatePresentation(
|
||||
title = updatedVersion?.let { "Updated to $it" } ?: "Up to date",
|
||||
summary = if (updatedVersion != null) "Sign-ins and settings kept." else "No newer release for this TV.",
|
||||
actions = listOf(UpdateAction("Check again", UpdateCommand.Check, true)),
|
||||
)
|
||||
UpdateUiState.UpToDate -> updatedVersion?.let(::updatedPresentation)
|
||||
?: UpdatePresentation("Up to date", "No newer release for this TV.",
|
||||
actions = listOf(UpdateAction("Check again", UpdateCommand.Check, true)))
|
||||
UpdateUiState.NoReleasePublished -> UpdatePresentation("No release published", "No update has been published for this TV yet.",
|
||||
actions = listOf(UpdateAction("Check again", UpdateCommand.Check, true)))
|
||||
is UpdateUiState.Available -> UpdatePresentation("Update available", updateMetadata(state),
|
||||
|
|
@ -66,7 +65,7 @@ fun presentUpdate(state: UpdateUiState, release: UpdateUiState.Available?, updat
|
|||
listOf("Wolfskin closes during installation.", "Choose Open, or reopen Wolfskin from the launcher."), listOf(UpdateAction("Back", UpdateCommand.Cancel)))
|
||||
UpdateUiState.InstallCancelled -> UpdatePresentation("Install cancelled", metadata,
|
||||
listOf("Verified · your sign-ins and settings stay."), listOf(UpdateAction("Try install again", UpdateCommand.Install, true), notes))
|
||||
is UpdateUiState.Failed -> UpdatePresentation(failureTitle(state.kind), state.message, actions = listOf(retry, back))
|
||||
is UpdateUiState.Failed -> UpdatePresentation(failureTitle(state.kind, state.operation), state.message, actions = listOf(retry, back))
|
||||
UpdateUiState.Offline -> UpdatePresentation("No network", "Reconnect this TV, then try again.",
|
||||
actions = listOf(UpdateAction("Try again", UpdateCommand.Retry, true)))
|
||||
UpdateUiState.NoInstaller -> UpdatePresentation("This TV cannot open an installer", "Android’s install confirmation is unavailable.",
|
||||
|
|
@ -75,9 +74,19 @@ fun presentUpdate(state: UpdateUiState, release: UpdateUiState.Available?, updat
|
|||
}
|
||||
}
|
||||
|
||||
private fun failureTitle(kind: UpdateFailure): String = when (kind) {
|
||||
UpdateFailure.Network -> "Check failed"
|
||||
UpdateFailure.HttpRefused, UpdateFailure.InsufficientStorage -> "Download failed"
|
||||
UpdateFailure.InvalidMetadata, UpdateFailure.UnsupportedAbi -> "Update unavailable"
|
||||
UpdateFailure.ChecksumMismatch, UpdateFailure.WrongPackage, UpdateFailure.WrongSigner, UpdateFailure.LowerVersionCode -> "Verification failed"
|
||||
private fun updatedPresentation(version: String) = UpdatePresentation(
|
||||
"Updated to $version", "Sign-ins and settings kept.",
|
||||
actions = listOf(UpdateAction("Check again", UpdateCommand.Check, true)),
|
||||
)
|
||||
|
||||
private fun failureTitle(kind: UpdateFailure, operation: UpdateOperation): String {
|
||||
if (operation == UpdateOperation.Install) return "Install failed"
|
||||
return when (kind) {
|
||||
UpdateFailure.Network, UpdateFailure.HttpRefused, UpdateFailure.InsufficientStorage ->
|
||||
if (operation == UpdateOperation.Check) "Check failed" else "Download failed"
|
||||
UpdateFailure.InvalidMetadata ->
|
||||
if (operation == UpdateOperation.Check) "Update unavailable" else "Verification failed"
|
||||
UpdateFailure.UnsupportedAbi -> "Update unavailable"
|
||||
UpdateFailure.ChecksumMismatch, UpdateFailure.WrongPackage, UpdateFailure.WrongSigner, UpdateFailure.LowerVersionCode -> "Verification failed"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -71,10 +71,10 @@ fun UpdatesScreen(shell: ShellState, controller: UpdateController, onBack: () ->
|
|||
val installed by controller.installedVersion.collectAsStateWithLifecycle()
|
||||
val release by controller.release.collectAsStateWithLifecycle()
|
||||
val autoCheck by controller.autoCheck.collectAsStateWithLifecycle()
|
||||
val initialInstalled = remember { installed.versionName }
|
||||
val updatedVersion = installed.versionName.takeIf { it != initialInstalled }
|
||||
val initialInstalledCode = remember { installed.versionCode }
|
||||
val updatedVersion = installed.versionName.takeIf { installed.versionCode > initialInstalledCode }
|
||||
val presentation = remember(state, release, updatedVersion) {
|
||||
presentUpdate(state, release, updatedVersion.takeIf { state == UpdateUiState.UpToDate })
|
||||
presentUpdate(state, release, updatedVersion.takeIf { state == UpdateUiState.Idle || state == UpdateUiState.UpToDate })
|
||||
}
|
||||
val scroll = rememberScrollState()
|
||||
val scope = rememberCoroutineScope()
|
||||
|
|
|
|||
|
|
@ -3,6 +3,12 @@ package org.justinvisser.wolfskin.tv.update
|
|||
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
|
||||
/** Actual APK identity, read independently of channel metadata. */
|
||||
data class ApkIdentity(val packageId: String, val version: InstalledVersion, val signers: Set<String>)
|
||||
|
|
@ -13,12 +19,15 @@ interface UpdatePlatform {
|
|||
fun inspect(file: File): ApkIdentity?
|
||||
fun hasInstallPermission(): Boolean
|
||||
fun openPermissionSettings(): Boolean
|
||||
fun install(file: File, outcome: (InstallOutcome) -> Unit)
|
||||
fun install(file: File, asset: UpdateAsset, outcome: (InstallOutcome) -> Unit)
|
||||
}
|
||||
|
||||
/** Installer results do not imply the running process has been replaced. */
|
||||
enum class InstallOutcome { Pending, Success, Cancelled, Failed, Unavailable, InsufficientStorage }
|
||||
|
||||
/** Metadata returned only after verifying the persisted APK against this release. */
|
||||
data class VerifiedRelease(val manifest: UpdateManifest, val asset: UpdateAsset, val notes: String)
|
||||
|
||||
/** Private staging; a metadata commit occurs only after independently verifying the APK. */
|
||||
class VerifiedUpdateStore(val directory: File, private val platform: UpdatePlatform) {
|
||||
val partial = File(directory, "download.part")
|
||||
|
|
@ -52,23 +61,28 @@ class VerifiedUpdateStore(val directory: File, private val platform: UpdatePlatf
|
|||
}
|
||||
}
|
||||
|
||||
fun commit(manifest: UpdateManifest, asset: UpdateAsset) {
|
||||
fun commit(manifest: UpdateManifest, asset: UpdateAsset, notes: String) {
|
||||
verify(partial, manifest, asset)
|
||||
check(partial.renameTo(apk)) { "Could not commit verified APK" }
|
||||
val temporary = File(directory, "ready.pending")
|
||||
temporary.outputStream().use { it.write(UpdateManifest.encode(manifest).toByteArray()); it.fd.sync() }
|
||||
val metadata = Json.parseToJsonElement(UpdateManifest.encode(manifest)).jsonObject
|
||||
val stored = JsonObject(metadata + ("releaseNotes" to JsonPrimitive(notes)))
|
||||
temporary.outputStream().use { it.write(stored.toString().toByteArray()); it.fd.sync() }
|
||||
check(temporary.renameTo(record)) { "Could not commit verified metadata" }
|
||||
}
|
||||
|
||||
/** Re-hash and re-inspect after process death; a marker alone never establishes trust. */
|
||||
fun restore(abis: List<String>, sdk: Int): UpdateManifest? {
|
||||
fun restore(abis: List<String>, sdk: Int): VerifiedRelease? {
|
||||
partial.delete()
|
||||
File(directory, "ready.pending").delete()
|
||||
if (!record.exists()) { apk.delete(); return null }
|
||||
return try {
|
||||
val manifest = UpdateManifest.parse(record.readText())
|
||||
verify(apk, manifest, manifest.selectAsset(abis, sdk))
|
||||
manifest
|
||||
val text = record.readText()
|
||||
val manifest = UpdateManifest.parse(text)
|
||||
val asset = manifest.selectAsset(abis, sdk)
|
||||
verify(apk, manifest, asset)
|
||||
val notes = Json.parseToJsonElement(text).jsonObject["releaseNotes"]?.jsonPrimitive?.contentOrNull.orEmpty()
|
||||
VerifiedRelease(manifest, asset, notes)
|
||||
} catch (_: Exception) { clear(); null }
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue