diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 667b543e..6aee8da6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -102,6 +102,10 @@ jobs: # installs (must keep "universal" in the name so the updater's asset selector picks it). # End users get diagnostics from the in-app export, so no debug APK is distributed. cp app/build/outputs/apk/release/app-universal-release.apk "dist/pulseloop-${V}-universal.apk" + # The app installs an update only when its SHA-256 matches this file (Gabriel Design + # System, docs/self-update.md), so every release must carry it. + (cd dist && sha256sum *.apk > SHA256SUMS.txt) + cat dist/SHA256SUMS.txt ls -la dist - name: Create / update release and attach APKs @@ -112,4 +116,6 @@ jobs: name: PulseLoop ${{ steps.ver.outputs.name }} (${{ steps.ver.outputs.code }}) prerelease: ${{ steps.ver.outputs.prerelease }} generate_release_notes: true - files: dist/*.apk + files: | + dist/*.apk + dist/SHA256SUMS.txt diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index ddb629e9..a1aa1dc3 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -1977,5 +1977,24 @@ "{0}{1} {2} in 90 days": "{0}{1} {2} em 90 dias", "±{0}m · {1} pts": "±{0}m · {1} pts", "−%.1f °C from your usual": "−%.1f °C em relação ao seu habitual", - "≈ {0} kcal · {1} g protein · leaves {2} kcal": "≈ {0} kcal · {1} g de proteína · sobram {2} kcal" + "≈ {0} kcal · {1} g protein · leaves {2} kcal": "≈ {0} kcal · {1} g de proteína · sobram {2} kcal", + "Update available · {0}": "Atualização disponível · {0}", + "Update": "Atualizar", + "Update · {0}": "Atualizar · {0}", + "Downloading… {0}%": "Baixando… {0}%", + "Check for updates": "Procurar atualizações", + "Checking…": "Procurando…", + "You're on the latest version ({0}).": "Você está na versão mais recente ({0}).", + "Couldn't check for updates ({0}). Try again.": "Não foi possível procurar atualizações ({0}). Tente de novo.", + "Download failed. Try again.": "O download falhou. Tente de novo.", + "The download didn't match the release's checksum, so it wasn't installed.": "O download não confere com a soma de verificação da versão, então não foi instalado.", + "The download isn't signed like this app, so it wasn't installed.": "O download não tem a mesma assinatura deste app, então não foi instalado.", + "Allow installs from this app, then tap Update again.": "Permita instalações deste app e toque em Atualizar de novo.", + "Self-update works in the release build only ({0} / {1}).": "A atualização automática só funciona na versão de lançamento ({0} / {1}).", + "A new version is available.": "Uma nova versão está disponível.", + "no connection": "sem conexão", + "GitHub is busy, try again in an hour": "o GitHub está ocupado, tente de novo em uma hora", + "GitHub didn't answer": "o GitHub não respondeu", + "unexpected reply from GitHub": "resposta inesperada do GitHub", + "the release has no checksum": "a versão não tem soma de verificação" } diff --git a/app/src/main/java/com/pulseloop/update/ApkInstaller.kt b/app/src/main/java/com/pulseloop/update/ApkInstaller.kt index 160d88af..16bad93d 100644 --- a/app/src/main/java/com/pulseloop/update/ApkInstaller.kt +++ b/app/src/main/java/com/pulseloop/update/ApkInstaller.kt @@ -2,7 +2,10 @@ package com.pulseloop.update import android.content.Context import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.Signature import android.net.Uri +import android.os.Build import android.provider.Settings import androidx.core.content.FileProvider import java.io.File @@ -26,6 +29,29 @@ object ApkInstaller { fun installPermissionIntent(context: Context): Intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${context.packageName}")) + /** + * The downloaded file is this app (same package) signed with the installed app's key. Android's + * installer would refuse a different key too, but only after the confirmation; this says why + * first and never offers it (Gabriel Design System, docs/self-update.md). + */ + fun sameAppAndKey(context: Context, apk: File): Boolean = try { + val pm = context.packageManager + val archive = pm.getPackageArchiveInfo(apk.path, signingFlag()) + val installed = pm.getPackageInfo(context.packageName, signingFlag()) + archive != null && archive.packageName == context.packageName && + signers(archive)?.toSet()?.let { it.isNotEmpty() && it == signers(installed)?.toSet() } == true + } catch (_: Exception) { + false + } + + @Suppress("DEPRECATION") + private fun signingFlag(): Int = + if (Build.VERSION.SDK_INT >= 28) PackageManager.GET_SIGNING_CERTIFICATES else PackageManager.GET_SIGNATURES + + @Suppress("DEPRECATION") + private fun signers(info: android.content.pm.PackageInfo): Array? = + if (Build.VERSION.SDK_INT >= 28) info.signingInfo?.apkContentsSigners else info.signatures + fun install(context: Context, apk: File) { val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", apk) val intent = Intent(Intent.ACTION_VIEW).apply { diff --git a/app/src/main/java/com/pulseloop/update/UpdateChecker.kt b/app/src/main/java/com/pulseloop/update/UpdateChecker.kt index b639cb80..dce3162c 100644 --- a/app/src/main/java/com/pulseloop/update/UpdateChecker.kt +++ b/app/src/main/java/com/pulseloop/update/UpdateChecker.kt @@ -11,7 +11,11 @@ import kotlinx.serialization.json.Json import okhttp3.OkHttpClient import okhttp3.Request import java.io.File +import java.security.MessageDigest +import java.util.Locale import java.util.concurrent.TimeUnit +import kotlin.coroutines.coroutineContext +import kotlinx.coroutines.ensureActive @Serializable data class GithubRelease( @@ -39,8 +43,19 @@ data class UpdateInfo( val apkUrl: String, val apkSize: Long, val htmlUrl: String, + val apkName: String = "", + /** Where the release's SHA256SUMS.txt is, if it has one. */ + val sumsUrl: String? = null, + /** The APK's SHA-256 from that file (lowercase hex). No sum, no update. */ + val sha256: String = "", ) +/** Outcome of [UpdateChecker.download]: the verified file, or why there is none (an English key for `tr`). */ +sealed class DownloadResult { + data class Ready(val file: File) : DownloadResult() + data class Failed(val reason: String) : DownloadResult() +} + /** * Outcome of an update check. Failures are distinct from "no update" so the UI never * tells an offline or rate-limited user they're on the latest version. @@ -50,6 +65,7 @@ sealed class UpdateCheckResult { data object UpToDate : UpdateCheckResult() /** Unsupported build (debug / non-release id), or inside the auto-check throttle window. */ data object Skipped : UpdateCheckResult() + /** [reason] is a fixed English phrase, translated where it's shown. */ data class Failed(val reason: String) : UpdateCheckResult() } @@ -128,7 +144,7 @@ object UpdateChecker { val response = try { client.newCall(request).execute() } catch (_: Exception) { - return@withContext UpdateCheckResult.Failed("network error") + return@withContext UpdateCheckResult.Failed(REASON_OFFLINE) } response.use { resp -> @@ -140,21 +156,43 @@ object UpdateChecker { } else -> { edit.apply() - return@withContext UpdateCheckResult.Failed("GitHub returned ${resp.code}") + return@withContext UpdateCheckResult.Failed( + if (resp.code == 403 || resp.code == 429) REASON_RATE_LIMITED else REASON_NO_ANSWER, + ) } } edit.apply() - if (bodyText == null) return@withContext UpdateCheckResult.Failed("empty response") - evaluate(bodyText) + if (bodyText == null) return@withContext UpdateCheckResult.Failed(REASON_BAD_REPLY) + withChecksum(evaluate(bodyText)) } } + /** + * Fills in the APK's SHA-256 from the release's SHA256SUMS.txt (Gabriel Design System, + * docs/self-update.md: no published sum, no install). A release without the file, or without a + * line for this APK, is not offered: the check fails with a reason a manual check shows. + */ + private fun withChecksum(result: UpdateCheckResult): UpdateCheckResult { + if (result !is UpdateCheckResult.UpdateAvailable) return result + val info = result.info + val sumsUrl = info.sumsUrl ?: return UpdateCheckResult.Failed(REASON_NO_CHECKSUM) + val text = try { + client.newCall(Request.Builder().url(sumsUrl).build()).execute().use { r -> + if (!r.isSuccessful || !r.request.url.isHttps) null else r.body?.string() + } + } catch (_: Exception) { + return UpdateCheckResult.Failed(REASON_OFFLINE) + } ?: return UpdateCheckResult.Failed(REASON_NO_CHECKSUM) + val sum = parseSums(text)[info.apkName] ?: return UpdateCheckResult.Failed(REASON_NO_CHECKSUM) + return UpdateCheckResult.UpdateAvailable(info.copy(sha256 = sum)) + } + /** Compare a releases-API response body against the installed build. */ private fun evaluate(bodyText: String): UpdateCheckResult { val release = try { json.decodeFromString(GithubRelease.serializer(), bodyText) } catch (_: Exception) { - return UpdateCheckResult.Failed("unexpected response from GitHub") + return UpdateCheckResult.Failed(REASON_BAD_REPLY) } if (release.draft || release.prerelease) return UpdateCheckResult.UpToDate @@ -162,11 +200,9 @@ object UpdateChecker { ?: return UpdateCheckResult.UpToDate // tag not in the v+ scheme if (remoteCode <= BuildConfig.VERSION_CODE) return UpdateCheckResult.UpToDate - val apks = release.assets.filter { it.name.endsWith(".apk", ignoreCase = true) } - val apk = apks.firstOrNull { it.name.contains("universal", ignoreCase = true) } - ?: apks.firstOrNull { a -> Build.SUPPORTED_ABIS.any { a.name.contains(it, ignoreCase = true) } } - ?: apks.firstOrNull() - ?: return UpdateCheckResult.Failed("release has no APK asset") + val apk = chooseApk(release.assets, Build.SUPPORTED_ABIS.toList()) + ?: return UpdateCheckResult.UpToDate // nothing this phone can install: not an error to show + val sums = release.assets.firstOrNull { it.name == SUMS_FILE } return UpdateCheckResult.UpdateAvailable(UpdateInfo( versionName = versionNameFromTag(release.tagName), @@ -175,41 +211,78 @@ object UpdateChecker { apkUrl = apk.browserDownloadUrl, apkSize = apk.size, htmlUrl = release.htmlUrl ?: "", + apkName = apk.name, + sumsUrl = sums?.browserDownloadUrl?.takeIf { it.startsWith("https://") }, )) } + const val SUMS_FILE = "SHA256SUMS.txt" + const val REASON_OFFLINE = "no connection" + const val REASON_RATE_LIMITED = "GitHub is busy, try again in an hour" + const val REASON_NO_ANSWER = "GitHub didn't answer" + const val REASON_BAD_REPLY = "unexpected reply from GitHub" + const val REASON_NO_CHECKSUM = "the release has no checksum" + const val DOWNLOAD_FAILED = "Download failed. Try again." + const val CHECKSUM_MISMATCH = "The download didn't match the release's checksum, so it wasn't installed." + const val NOT_THIS_APP = "The download isn't signed like this app, so it wasn't installed." + + /** Universal APK first, then one for this phone's ABI, then any APK; HTTPS links only. */ + fun chooseApk(assets: List, abis: List): GithubAsset? { + val apks = assets.filter { it.name.endsWith(".apk", ignoreCase = true) && it.browserDownloadUrl.startsWith("https://") } + return apks.firstOrNull { it.name.contains("universal", ignoreCase = true) } + ?: apks.firstOrNull { a -> abis.any { a.name.contains(it, ignoreCase = true) } } + ?: apks.firstOrNull() + } + + /** `sha256sum` output ("<64 hex> name" or "<64 hex> *name") → file name → lowercase hex. */ + fun parseSums(text: String): Map = text.lineSequence().mapNotNull { line -> + val m = SUM_LINE.matchEntire(line.trim()) ?: return@mapNotNull null + m.groupValues[2].trim() to m.groupValues[1].lowercase(Locale.ROOT) + }.toMap() + + private val SUM_LINE = Regex("([0-9a-fA-F]{64})\\s+\\*?(.+)") + + /** "38 MB" for the Update button. */ + fun sizeLabel(bytes: Long): String = + if (bytes >= 1_000_000_000L) String.format(Locale.ROOT, "%.1f GB", bytes / 1e9) + else "${maxOf(1L, Math.round(bytes / 1e6))} MB" + /** - * Download the APK to cacheDir/updates, reporting progress in 0f..1f. Returns the file, or - * null if the download failed or arrived short. + * Downloads the APK to cacheDir/updates, reporting progress in 0f..1f, and checks it before + * anything is installed (Gabriel Design System, docs/self-update.md): HTTPS only, the whole file, + * its SHA-256 against the release's SHA256SUMS.txt, and the same package and signing key as this + * app. Cancelling the calling coroutine stops the download and deletes the part. * - * The short-file check is the important one: a body that ends early without throwing (a - * dropped connection on a chunked reply, a captive portal cutting in) leaves a truncated - * APK, and the system package installer reports that as "There was a problem parsing the - * package" — which reads as a broken release rather than a failed download. Better to fail - * the download honestly and let the user retry. + * The short-file check matters: a body that ends early without throwing (a dropped connection on + * a chunked reply, a captive portal cutting in) leaves a truncated APK, and the system installer + * reports that as "There was a problem parsing the package", which reads as a broken release. */ suspend fun download( context: Context, info: UpdateInfo, onProgress: (Float) -> Unit, - ): File? = withContext(Dispatchers.IO) { + ): DownloadResult = withContext(Dispatchers.IO) { + if (info.sha256.isEmpty()) return@withContext DownloadResult.Failed(CHECKSUM_MISMATCH) val dir = File(context.cacheDir, "updates").apply { mkdirs() } val out = File(dir, "pulseloop-${info.versionCode}.apk") try { downloadClient.newCall(Request.Builder().url(info.apkUrl).build()).execute().use { resp -> - if (!resp.isSuccessful) return@withContext null - val body = resp.body ?: return@withContext null + if (!resp.isSuccessful || !resp.request.url.isHttps) return@withContext DownloadResult.Failed(DOWNLOAD_FAILED) + val body = resp.body ?: return@withContext DownloadResult.Failed(DOWNLOAD_FAILED) val stream = body.byteStream() val total = body.contentLength().takeIf { it > 0 } ?: info.apkSize dir.listFiles()?.forEach { it.delete() } // drop any stale download + val sha = MessageDigest.getInstance("SHA-256") var downloaded = 0L out.outputStream().use { fos -> val buf = ByteArray(64 * 1024) var read: Int while (stream.read(buf).also { read = it } != -1) { + coroutineContext.ensureActive() // Cancel in the dialog fos.write(buf, 0, read) + sha.update(buf, 0, read) downloaded += read if (total > 0) onProgress((downloaded.toFloat() / total).coerceIn(0f, 1f)) } @@ -218,13 +291,26 @@ object UpdateChecker { if (total > 0 && downloaded != total) { out.delete() - return@withContext null + return@withContext DownloadResult.Failed(DOWNLOAD_FAILED) } - out + if (hex(sha.digest()) != info.sha256) { + out.delete() + return@withContext DownloadResult.Failed(CHECKSUM_MISMATCH) + } + if (!ApkInstaller.sameAppAndKey(context, out)) { + out.delete() + return@withContext DownloadResult.Failed(NOT_THIS_APP) + } + DownloadResult.Ready(out) } + } catch (cancelled: kotlinx.coroutines.CancellationException) { + out.delete() + throw cancelled } catch (_: Exception) { out.delete() - null + DownloadResult.Failed(DOWNLOAD_FAILED) } } + + fun hex(bytes: ByteArray): String = bytes.joinToString("") { String.format(Locale.ROOT, "%02x", it) } } diff --git a/app/src/main/java/com/pulseloop/update/UpdateUi.kt b/app/src/main/java/com/pulseloop/update/UpdateUi.kt index 031065d3..1dc26481 100644 --- a/app/src/main/java/com/pulseloop/update/UpdateUi.kt +++ b/app/src/main/java/com/pulseloop/update/UpdateUi.kt @@ -18,33 +18,46 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.pulseloop.BuildConfig +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics import com.pulseloop.ui.components.MarkdownLite +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf +import kotlinx.coroutines.Job import kotlinx.coroutines.launch /** - * "Update available" dialog: shows the changelog, then downloads the APK with a progress bar - * and hands it to the system installer. Reused by the on-launch check and the Settings button. + * "Update available" dialog (Gabriel Design System, docs/self-update.md): the changelog, then + * Update · size downloads the APK with a progress bar, checks it, and hands it to the system + * installer. While it downloads, Later becomes Cancel and the dialog can't be dismissed by accident. + * Reused by the foreground check and the About screen's button. */ @Composable fun UpdateDialog(info: UpdateInfo, onDismiss: () -> Unit) { val context = LocalContext.current val scope = rememberCoroutineScope() - var downloading by remember { mutableStateOf(false) } + var job by remember { mutableStateOf(null) } + val downloading = job != null var progress by remember { mutableFloatStateOf(0f) } var error by remember { mutableStateOf(null) } AlertDialog( onDismissRequest = { if (!downloading) onDismiss() }, - title = { Text("Update available — ${info.versionName}") }, + title = { Text(trf("Update available · {0}", info.versionName)) }, text = { Column { if (downloading) { - Text("Downloading… ${(progress * 100).toInt()}%", style = MaterialTheme.typography.bodyMedium) + Text( + trf("Downloading… {0}%", (progress * 100).toInt()), + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, + ) Spacer(Modifier.height(8.dp)) LinearProgressIndicator(progress = { progress }, modifier = Modifier.fillMaxWidth()) } else { MarkdownLite( - info.changelog, + tr(info.changelog), // GitHub's notes stay as written; the fallback line translates modifier = Modifier .heightIn(max = 320.dp) .verticalScroll(rememberScrollState()), @@ -58,7 +71,12 @@ fun UpdateDialog(info: UpdateInfo, onDismiss: () -> Unit) { ) error?.let { Spacer(Modifier.height(8.dp)) - Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, + ) } } } @@ -69,34 +87,45 @@ fun UpdateDialog(info: UpdateInfo, onDismiss: () -> Unit) { onClick = { // Require the per-app "install unknown apps" grant first. if (!ApkInstaller.canInstall(context)) { + error = tr("Allow installs from this app, then tap Update again.") context.startActivity(ApkInstaller.installPermissionIntent(context)) return@TextButton } - downloading = true error = null - scope.launch { - val file = UpdateChecker.download(context, info) { progress = it } - downloading = false - if (file != null) { - ApkInstaller.install(context, file) - onDismiss() - } else { - error = "Download failed. Please try again." + progress = 0f + job = scope.launch { + val result = UpdateChecker.download(context, info) { progress = it } + job = null + when (result) { + is DownloadResult.Ready -> { + ApkInstaller.install(context, result.file) + onDismiss() + } + is DownloadResult.Failed -> error = tr(result.reason) } } }, - ) { Text(if (downloading) "Downloading…" else "Update") } + ) { + Text( + if (info.apkSize > 0) trf("Update · {0}", UpdateChecker.sizeLabel(info.apkSize)) + else tr("Update"), + ) + } }, dismissButton = { - TextButton(enabled = !downloading, onClick = onDismiss) { Text("Later") } + if (downloading) { + TextButton(onClick = { job?.cancel(); job = null }) { Text(tr("Cancel")) } + } else { + TextButton(onClick = onDismiss) { Text(tr("Later")) } + } }, ) } /** - * Self-contained "Check for updates" control for the Settings screen: a button that runs a - * forced check and shows the result (up-to-date / error / the update dialog). On a debug or - * non-release build, self-update isn't possible, so it shows a short explanation instead. + * Self-contained "Check for updates" control for the About screen: a button that runs a forced + * check and shows the result (up to date / couldn't check / the update dialog). A debug or + * non-release build can't update itself, so it says that instead. */ @Composable fun CheckForUpdatesButton(modifier: Modifier = Modifier) { @@ -109,8 +138,7 @@ fun CheckForUpdatesButton(modifier: Modifier = Modifier) { Column(modifier) { if (!UpdateChecker.isSupported()) { Text( - "Self-update is available in the release build only " + - "(current: ${BuildConfig.VERSION_NAME} / ${BuildConfig.APPLICATION_ID}).", + trf("Self-update works in the release build only ({0} / {1}).", BuildConfig.VERSION_NAME, BuildConfig.APPLICATION_ID), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -125,17 +153,22 @@ fun CheckForUpdatesButton(modifier: Modifier = Modifier) { when (val result = UpdateChecker.check(context, force = true)) { is UpdateCheckResult.UpdateAvailable -> update = result.info is UpdateCheckResult.Failed -> - status = "Couldn't check for updates (${result.reason}). Please try again." - else -> status = "You're on the latest version (${BuildConfig.VERSION_NAME})." + status = trf("Couldn't check for updates ({0}). Try again.", tr(result.reason)) + else -> status = trf("You're on the latest version ({0}).", BuildConfig.VERSION_NAME) } checking = false } }, modifier = Modifier.fillMaxWidth(), - ) { Text(if (checking) "Checking…" else "Check for updates") } + ) { Text(if (checking) tr("Checking…") else tr("Check for updates")) } status?.let { Spacer(Modifier.height(8.dp)) - Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, + ) } } diff --git a/app/src/test/java/com/pulseloop/update/UpdateCheckerTest.kt b/app/src/test/java/com/pulseloop/update/UpdateCheckerTest.kt new file mode 100644 index 00000000..f31a426c --- /dev/null +++ b/app/src/test/java/com/pulseloop/update/UpdateCheckerTest.kt @@ -0,0 +1,48 @@ +package com.pulseloop.update + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** The pure parts of the self-update rules (Gabriel Design System, docs/self-update.md). */ +class UpdateCheckerTest { + private val sum = "a".repeat(64) + private val other = "B".repeat(64) + + @Test + fun `sha256sum output maps file names to lowercase sums`() { + val sums = UpdateChecker.parseSums("$sum pulseloop-2.11.54+129-universal.apk\n$other *GMind-0.5.246.apk\n\nnot a line\n") + assertEquals(sum, sums["pulseloop-2.11.54+129-universal.apk"]) + assertEquals("b".repeat(64), sums["GMind-0.5.246.apk"]) + assertEquals(2, sums.size) + } + + @Test + fun `universal APK first, then this phone's ABI, then any, and only over https`() { + fun a(name: String, url: String = "https://example.test/$name") = GithubAsset(name, url) + val assets = listOf(a("x-arm64-v8a.apk"), a("x-universal.apk"), a("SHA256SUMS.txt")) + assertEquals("x-universal.apk", UpdateChecker.chooseApk(assets, listOf("arm64-v8a"))?.name) + assertEquals("x-arm64-v8a.apk", UpdateChecker.chooseApk(assets.take(1) + a("x-x86.apk"), listOf("arm64-v8a"))?.name) + assertEquals("x-x86.apk", UpdateChecker.chooseApk(listOf(a("x-x86.apk")), listOf("arm64-v8a"))?.name) + assertNull(UpdateChecker.chooseApk(listOf(a("x-universal.apk", "http://example.test/x")), listOf("arm64-v8a"))) + assertNull(UpdateChecker.chooseApk(listOf(a("notes.txt")), listOf("arm64-v8a"))) + } + + @Test + fun `size label for the Update button`() { + assertEquals("38 MB", UpdateChecker.sizeLabel(38_200_000)) + assertEquals("1 MB", UpdateChecker.sizeLabel(10_000)) + assertEquals("1.2 GB", UpdateChecker.sizeLabel(1_200_000_000)) + } + + @Test + fun `digest as lowercase hex`() { + assertEquals("00ff10", UpdateChecker.hex(byteArrayOf(0, -1, 16))) + } + + @Test + fun `version from the tag`() { + assertEquals(129, UpdateChecker.versionCodeFromTag("v2.11.54+129")) + assertEquals("2.11.54", UpdateChecker.versionNameFromTag("v2.11.54+129")) + } +}