diff --git a/CHANGELOG.md b/CHANGELOG.md
index 572647f..64e05f8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,40 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
Nothing yet. Open an issue or PR to propose something.
+## [1.1.1] - 2026-10-22
+
+The app can now find and install its own updates, and its Settings screen has an About section that
+shows what changed in the latest release.
+
+### Added
+
+- **Check for updates.** A new *Updates* card in Settings. It reports whether a newer version has
+ been published, and downloads and starts the installation of it without the user having to find
+ the release page first. Nothing is fetched until the button is pressed, and nothing is downloaded
+ until the download is asked for.
+- **About / What's New.** A dialog showing the version installed on the device, the latest
+ published version, when it was published, and the release notes for it. The notes come from the
+ official GitHub release, so they are the same notes the release page shows. A copy is kept on the
+ device, so the dialog still says something useful when there is no network.
+- **The update flow respects the platform's safeguards.** The downloaded package is handed to
+ Android's own installer, which asks the user to confirm. On Android 8 and above the "install
+ unknown apps" permission is granted separately, in system settings, and the app says so and
+ takes the user there.
+
+### Fixed
+
+- **A release signed with the wrong key installed once and then refused to update.** The release
+ workflow now restores the keystore from a repository secret, verifies the signature before
+ publishing, and refuses to publish at all if the secret is missing.
+
+### Security
+
+- The release check uses GitHub's public API **without a token**. A token embedded in an
+ application can be extracted from every user's device; the endpoint is public, and the result is
+ cached so it is not hammered.
+- Release notes are rendered from a deliberately small Markdown subset. HTML is stripped, and a
+ link in somebody else's release notes is shown as text rather than made tappable.
+
## [1.1.0] - 2026-10-20
Deal alerts: the app now tells you when a game you saved goes on sale, and when a game becomes
@@ -189,8 +223,7 @@ failure mode behind every one.
- **Price history is local.** The chart shows prices *this device* recorded. External databases are
reachable through deep links rather than being scraped, because most of them block programmatic
access.
-
-[1.0.0]: https://github.com/JuggyBob/DiscountHunterAndroid/releases/tag/v1.0.0
-
-[Unreleased]: https://github.com/JuggyBob/DiscountHunterAndroid/compare/v1.1.0...HEAD
+[Unreleased]: https://github.com/JuggyBob/DiscountHunterAndroid/compare/v1.1.1...HEAD
+[1.1.1]: https://github.com/JuggyBob/DiscountHunterAndroid/releases/tag/v1.1.1
[1.1.0]: https://github.com/JuggyBob/DiscountHunterAndroid/releases/tag/v1.1.0
+[1.0.0]: https://github.com/JuggyBob/DiscountHunterAndroid/releases/tag/v1.0.0
\ No newline at end of file
diff --git a/README.md b/README.md
index f23e0d2..2ce3eb1 100644
--- a/README.md
+++ b/README.md
@@ -27,6 +27,7 @@ games to watch their prices.
| πΌοΈ **Rich detail pages** | Hero art, screenshots, trailers, system requirements, genres, "Where to buy" comparing every store that has the game |
| π **Price history** | A chart of prices **this device** recorded, with deep links to external databases |
| π¨ **Material You** | Follows your system light/dark theme, edge-to-edge, with hand-tuned motion throughout |
+| π **In-app updates** | Check the official releases from Settings, download a newer version and start Android's installer for it. Plus an About dialog with the release notes |
| π **Private by design** | No account, no tracking, no analytics, no API keys. Everything is cached on-device |
@@ -35,12 +36,17 @@ games to watch their prices.
-## What is new in 1.1.0
+## What is new in 1.1.1
+
+**The app can now update itself.** Settings has a *Check for updates* entry that finds a newer
+release, downloads it, and starts Android's own installer for it β and an *About* dialog that shows
+the version you are on, the version published most recently, and the release notes for it, fetched
+from the official GitHub release.
+
+Nothing is fetched until you ask, nothing is downloaded until you ask for that, and the
+installation itself is still confirmed by Android, in the normal way. See
+[CHANGELOG.md](CHANGELOG.md) for the full list.
-**Deal alerts.** The app now tells you when a game you saved goes on sale, and when a game becomes
-free to keep β with the name, the new price and the discount β and it does so **with the app
-closed**. See [CHANGELOG.md](CHANGELOG.md) for the full list, including the five bugs this release
-fixes along the way.
## Download
@@ -135,6 +141,7 @@ app/src/main/java/com/discounthunter/android/
β βββ cache/ # Region-scoped snapshots, payload cache
β βββ repo/ # Repositories merging the stores together
βββ alerts/ # Background deal alerts: detection, scheduling, notification
+βββ update/ # In-app updater: release metadata, download, install
βββ diagnostics/ # In-app log + crash capture used by the export button
βββ di/ # AppContainer β the hand-rolled dependency graph
βββ ui/ # Compose screens, one package per screen, plus shared components
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 963fef0..f4b1ca6 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -37,8 +37,8 @@ android {
targetSdk = 36
// Must be higher than any build already installed on a user's device, or the install is
// refused as a downgrade. The device this was built against had 1.0.1-release at code 7.
- versionCode = 8
- versionName = "1.1.0-release"
+ versionCode = 9
+ versionName = "1.1.1-release"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index a76e6bb..e50844d 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -18,6 +18,15 @@
-->
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/java/com/discounthunter/android/data/cache/CacheKey.kt b/app/src/main/java/com/discounthunter/android/data/cache/CacheKey.kt
index 66a696c..deaa839 100644
--- a/app/src/main/java/com/discounthunter/android/data/cache/CacheKey.kt
+++ b/app/src/main/java/com/discounthunter/android/data/cache/CacheKey.kt
@@ -57,4 +57,9 @@ object CacheKeys {
// ---- Epic --------------------------------------------------------------------------
fun epicFreeGames(country: String) = CacheKey("epic", "freegames", country, "v3")
+
+ // ---- GitHub -------------------------------------------------------------------------
+ // The application's own release metadata, used by the in-app updater and the about screen.
+ fun githubLatestRelease(owner: String, repository: String) =
+ CacheKey("github", "latest-release", owner, repository, "v1")
}
diff --git a/app/src/main/java/com/discounthunter/android/data/net/Outcome.kt b/app/src/main/java/com/discounthunter/android/data/net/Outcome.kt
index f103cee..ff8b581 100644
--- a/app/src/main/java/com/discounthunter/android/data/net/Outcome.kt
+++ b/app/src/main/java/com/discounthunter/android/data/net/Outcome.kt
@@ -45,4 +45,17 @@ inline fun Outcome.map(transform: (T) -> R): Outcome = when (this)
is Outcome.Failure -> this
}
+/**
+ * Collapses an outcome into a single value, handling both branches.
+ *
+ * The same shape as [Result.fold], so that a caller reading either one knows what to expect.
+ */
+inline fun Outcome.fold(
+ onSuccess: (T) -> R,
+ onFailure: (Outcome.Failure) -> R,
+): R = when (this) {
+ is Outcome.Success -> onSuccess(value)
+ is Outcome.Failure -> onFailure(this)
+}
+
fun Outcome.valueOrNull(): T? = (this as? Outcome.Success)?.value
diff --git a/app/src/main/java/com/discounthunter/android/di/AppContainer.kt b/app/src/main/java/com/discounthunter/android/di/AppContainer.kt
index 384a385..1443bf9 100644
--- a/app/src/main/java/com/discounthunter/android/di/AppContainer.kt
+++ b/app/src/main/java/com/discounthunter/android/di/AppContainer.kt
@@ -93,6 +93,15 @@ class AppContainer(
*/
private val payloadCache = PayloadCache(File(appContext.cacheDir, "http_cache"))
+ /**
+ * The raw-payload cache, shared with the release-metadata service.
+ *
+ * Public because the updater caches the release feed through it, so that the About screen can
+ * still show something useful when the network is unavailable. Using the same cache as the
+ * stores means there is one place that decides how long a payload is fresh.
+ */
+ val payloadCacheForUpdates: PayloadCache get() = payloadCache
+
/**
* Snapshots live in `filesDir`: they are browsable history, not a disposable cache, so they
* must survive the system clearing `cacheDir`.
diff --git a/app/src/main/java/com/discounthunter/android/ui/settings/AboutDialog.kt b/app/src/main/java/com/discounthunter/android/ui/settings/AboutDialog.kt
new file mode 100644
index 0000000..e2049fa
--- /dev/null
+++ b/app/src/main/java/com/discounthunter/android/ui/settings/AboutDialog.kt
@@ -0,0 +1,428 @@
+package com.discounthunter.android.ui.settings
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.AnnotatedString
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.SpanStyle
+import androidx.compose.ui.text.buildAnnotatedString
+import androidx.compose.ui.text.withStyle
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontStyle
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import com.discounthunter.android.R
+import com.discounthunter.android.update.InstallResults
+import com.discounthunter.android.update.ReleaseInfo
+import com.discounthunter.android.update.ReleaseNotesFormatter
+import com.discounthunter.android.update.UpdateState
+
+/**
+ * The About / What's New dialog.
+ *
+ * ## The one thing this must not get wrong
+ *
+ * There are two versions on screen and they are not the same thing: the version **installed** on
+ * this device, and the version **published** most recently. They are labelled separately, always,
+ * and the release notes are headed with the published version. A user who reads "1.1.1" under a
+ * heading that implies they have it, when they have 1.1.0, will be told to look for a feature
+ * that is not in their build.
+ *
+ * So: the installed version is shown under "Installed", the published one under "Latest release",
+ * and the notes are under "What's new in ".
+ */
+@Composable
+fun AboutDialog(
+ installedVersionName: String,
+ updateState: UpdateState,
+ release: ReleaseInfo?,
+ installResult: InstallResults.State?,
+ onCheckForUpdates: () -> Unit,
+ onDownload: () -> Unit,
+ onInstall: () -> Unit,
+ onCancel: () -> Unit,
+ onOpenReleasePage: (String) -> Unit,
+ onDismiss: () -> Unit,
+) {
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text(stringResource(R.string.about_title)) },
+ text = {
+ Column(
+ modifier = Modifier
+ .heightIn(max = 420.dp)
+ .verticalScroll(rememberScrollState()),
+ ) {
+ Text(
+ text = stringResource(R.string.about_name),
+ style = MaterialTheme.typography.titleSmall,
+ )
+ Spacer(Modifier.height(8.dp))
+
+ LabelValue(
+ label = stringResource(R.string.about_installed),
+ value = installedVersionName,
+ )
+ release?.let { info ->
+ LabelValue(
+ label = stringResource(R.string.about_latest),
+ value = info.versionLabel,
+ )
+ if (info.publishedAt.isNotBlank()) {
+ LabelValue(
+ label = stringResource(R.string.about_published),
+ value = formatPublished(info.publishedAt),
+ )
+ }
+ }
+
+ Spacer(Modifier.height(14.dp))
+ InstallOutcomeText(installResult)
+ Spacer(Modifier.height(14.dp))
+ UpdateStatus(
+ state = updateState,
+ onCheckForUpdates = onCheckForUpdates,
+ onDownload = onDownload,
+ onInstall = onInstall,
+ onCancel = onCancel,
+ )
+
+ release?.let { info ->
+ Spacer(Modifier.height(16.dp))
+ HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
+ Spacer(Modifier.height(14.dp))
+ Text(
+ text = stringResource(
+ R.string.about_whats_new,
+ info.versionLabel,
+ ),
+ style = MaterialTheme.typography.titleSmall,
+ color = MaterialTheme.colorScheme.primary,
+ )
+ Spacer(Modifier.height(8.dp))
+ ReleaseNotes(info.body)
+ }
+
+ Spacer(Modifier.height(16.dp))
+ OutlinedButton(
+ onClick = {
+ onOpenReleasePage(release?.htmlUrl ?: DEFAULT_RELEASE_PAGE)
+ },
+ ) {
+ Text(stringResource(R.string.about_view_on_github))
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.about_close)) }
+ },
+ )
+}
+
+/**
+ * The outcome of the last installation attempt.
+ *
+ * Shown so the user is not left guessing whether the update went through: the system
+ * installer takes over the screen, and when it finishes the application has to say what
+ * happened.
+ */
+@Composable
+private fun InstallOutcomeText(state: InstallResults.State?) {
+ when (state) {
+ is InstallResults.State.AwaitingConfirmation -> Text(
+ text = stringResource(R.string.update_install_awaiting),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.primary,
+ )
+
+ is InstallResults.State.Completed -> Text(
+ text = stringResource(R.string.update_install_done),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.primary,
+ )
+
+ is InstallResults.State.Failed -> Text(
+ text = stringResource(R.string.update_install_error),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.error,
+ )
+
+ null -> Unit
+ }
+}
+
+/** A label and its value, stacked. */
+@Composable
+private fun LabelValue(label: String, value: String) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = 2.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(
+ text = label,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.width(112.dp),
+ )
+ Text(text = value, style = MaterialTheme.typography.bodyMedium)
+ }
+}
+
+/**
+ * The update status, and the action that matches it.
+ *
+ * Exactly one action is offered at a time, and the state names decide which: a check while idle,
+ * a download when an update exists, and a retry when something failed. The alternative β a button
+ * that changes meaning under the user β is how a check ends up firing twice.
+ */
+@Composable
+private fun UpdateStatus(
+ state: UpdateState,
+ onCheckForUpdates: () -> Unit,
+ onDownload: () -> Unit,
+ onInstall: () -> Unit,
+ onCancel: () -> Unit,
+) {
+ when (state) {
+ is UpdateState.Idle -> {
+ Text(
+ text = stringResource(R.string.update_idle),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Spacer(Modifier.height(8.dp))
+ OutlinedButton(onClick = onCheckForUpdates) {
+ Text(stringResource(R.string.update_check))
+ }
+ }
+
+ is UpdateState.Checking -> {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ CircularProgressIndicator(
+ modifier = Modifier.height(16.dp).width(16.dp),
+ strokeWidth = 2.dp,
+ )
+ Spacer(Modifier.width(10.dp))
+ Text(
+ text = stringResource(R.string.update_checking),
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ }
+ }
+
+ is UpdateState.UpToDate -> {
+ Text(
+ text = stringResource(R.string.update_up_to_date),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.primary,
+ )
+ }
+
+ is UpdateState.Available -> {
+ Text(
+ text = stringResource(
+ R.string.update_available,
+ state.installed.toString(),
+ state.release.versionLabel,
+ ),
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ Spacer(Modifier.height(10.dp))
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ OutlinedButton(onClick = onDownload) {
+ Text(stringResource(R.string.update_download))
+ }
+ TextButton(onClick = onCheckForUpdates) {
+ Text(stringResource(R.string.update_recheck))
+ }
+ }
+ }
+
+ is UpdateState.Downloading -> {
+ Text(
+ text = stringResource(R.string.update_downloading),
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ Spacer(Modifier.height(8.dp))
+ LinearProgressIndicator(
+ progress = { state.fraction },
+ modifier = Modifier.fillMaxWidth(),
+ )
+ Spacer(Modifier.height(8.dp))
+ TextButton(onClick = onCancel) {
+ Text(stringResource(R.string.update_cancel))
+ }
+ }
+
+ is UpdateState.ReadyToInstall -> {
+ Text(
+ text = stringResource(R.string.update_ready),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.primary,
+ )
+ Spacer(Modifier.height(10.dp))
+ OutlinedButton(onClick = onInstall) {
+ Text(stringResource(R.string.update_install))
+ }
+ }
+
+ is UpdateState.Failed -> {
+ Text(
+ text = state.message,
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.error,
+ )
+ if (state.retryable) {
+ Spacer(Modifier.height(8.dp))
+ OutlinedButton(onClick = onCheckForUpdates) {
+ Text(stringResource(R.string.update_retry))
+ }
+ }
+ }
+
+ is UpdateState.NoInstallableAsset -> {
+ Text(
+ text = state.reason,
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.error,
+ )
+ Spacer(Modifier.height(8.dp))
+ Text(
+ text = stringResource(R.string.update_no_package),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+}
+
+/**
+ * The release notes, rendered from the limited Markdown subset.
+ *
+ * Scrolls with the rest of the dialog, so a long changelog does not push the close button off the
+ * screen.
+ */
+@Composable
+private fun ReleaseNotes(body: String) {
+ val lines = remember(body) { ReleaseNotesFormatter.parse(body) }
+ if (lines.isEmpty()) {
+ Text(
+ text = stringResource(R.string.about_no_notes),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ return
+ }
+ Column {
+ for (line in lines) {
+ when (line.style) {
+ ReleaseNotesFormatter.Style.RULE -> {
+ Spacer(Modifier.height(8.dp))
+ HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
+ Spacer(Modifier.height(8.dp))
+ }
+
+ ReleaseNotesFormatter.Style.HEADING -> {
+ Spacer(Modifier.height(6.dp))
+ Text(
+ text = inline(line.text),
+ style = MaterialTheme.typography.titleSmall,
+ color = MaterialTheme.colorScheme.primary,
+ )
+ Spacer(Modifier.height(2.dp))
+ }
+
+ ReleaseNotesFormatter.Style.SUBHEADING -> {
+ Spacer(Modifier.height(4.dp))
+ Text(
+ text = inline(line.text),
+ style = MaterialTheme.typography.bodyMedium,
+ fontWeight = FontWeight.Bold,
+ )
+ }
+
+ ReleaseNotesFormatter.Style.BULLET -> {
+ Row(modifier = Modifier.padding(bottom = 4.dp)) {
+ Text(
+ text = "β’",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Spacer(Modifier.width(8.dp))
+ Text(
+ text = inline(line.text),
+ style = MaterialTheme.typography.bodySmall,
+ )
+ }
+ }
+
+ ReleaseNotesFormatter.Style.TEXT -> {
+ Text(
+ text = inline(line.text),
+ style = MaterialTheme.typography.bodySmall,
+ )
+ Spacer(Modifier.height(4.dp))
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Applies the inline styles to one line of text.
+ *
+ * The parsing lives in [ReleaseNotesFormatter], so it can be tested without a Compose runtime; this
+ * only turns the segments into a styled string.
+ */
+@Composable
+private fun inline(text: String): AnnotatedString {
+ val segments = remember(text) { ReleaseNotesFormatter.inline(text) }
+ return buildAnnotatedString {
+ for (segment in segments) {
+ withStyle(
+ SpanStyle(
+ fontWeight = if (segment.bold) FontWeight.Bold else null,
+ fontStyle = if (segment.italic) FontStyle.Italic else null,
+ fontFamily = if (segment.code) FontFamily.Monospace else null,
+ ),
+ ) {
+ append(segment.text)
+ }
+ }
+ }
+}
+/** Formats a GitHub timestamp as a plain date. */
+private fun formatPublished(publishedAt: String): String = runCatching {
+ val instant = java.time.Instant.parse(publishedAt)
+ val formatter = java.time.format.DateTimeFormatter
+ .ofLocalizedDate(java.time.format.FormatStyle.LONG)
+ .withZone(java.time.ZoneId.systemDefault())
+ formatter.format(instant)
+}.getOrDefault(publishedAt)
+
+/** The official release page, used when no release metadata has been fetched yet. */
+private const val DEFAULT_RELEASE_PAGE =
+ "https://github.com/JuggyBob/DiscountHunterAndroid/releases/latest"
diff --git a/app/src/main/java/com/discounthunter/android/ui/settings/SettingsScreen.kt b/app/src/main/java/com/discounthunter/android/ui/settings/SettingsScreen.kt
index 64983de..9d3aa50 100644
--- a/app/src/main/java/com/discounthunter/android/ui/settings/SettingsScreen.kt
+++ b/app/src/main/java/com/discounthunter/android/ui/settings/SettingsScreen.kt
@@ -13,6 +13,8 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
+import android.content.Intent
+import android.net.Uri
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
@@ -57,6 +59,7 @@ import com.discounthunter.android.core.model.StoreId
import com.discounthunter.android.data.settings.AppSettings
import com.discounthunter.android.data.settings.CurrencyCode
import com.discounthunter.android.data.settings.ThemeMode
+import com.discounthunter.android.update.UpdateState
import kotlin.math.roundToInt
/**
@@ -78,6 +81,7 @@ fun SettingsScreen(
var accountFor by remember { mutableStateOf(null) }
var confirmClear by remember { mutableStateOf(false) }
var confirmDeleteAll by remember { mutableStateOf(false) }
+ var showAbout by remember { mutableStateOf(false) }
// The notification permission is requested from the screen, because a ViewModel has no
// activity to attach a permission dialog to. The request is made when the user switches the
@@ -379,6 +383,46 @@ fun SettingsScreen(
}
}
+ // ---- updates ----
+ //
+ // Its own card, above About, because checking for an update is a deliberate action
+ // and not a detail of the application's identity. The status line reports what is
+ // known without the user having to open a dialog to find out.
+ SettingsCard(title = stringResource(R.string.settings_updates)) {
+ val updateState by viewModel.updateState.collectAsStateWithLifecycle()
+ val latestRelease by viewModel.latestRelease.collectAsStateWithLifecycle()
+ val installResult by viewModel.installResult.collectAsStateWithLifecycle()
+
+ Text(
+ text = when (val current = updateState) {
+ is UpdateState.Checking -> stringResource(R.string.update_checking)
+ is UpdateState.UpToDate -> stringResource(R.string.update_up_to_date)
+ is UpdateState.Available -> stringResource(
+ R.string.update_available,
+ current.installed.toString(),
+ current.release.versionLabel,
+ )
+ is UpdateState.Downloading -> stringResource(R.string.update_downloading)
+ is UpdateState.ReadyToInstall -> stringResource(R.string.update_ready)
+ is UpdateState.Failed -> current.message
+ is UpdateState.NoInstallableAsset -> current.reason
+ UpdateState.Idle -> latestRelease
+ ?.let { stringResource(R.string.about_latest) + ": " + it.versionLabel }
+ ?: stringResource(R.string.settings_updates_summary)
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Spacer(Modifier.height(10.dp))
+ OutlinedButton(
+ onClick = { viewModel.checkForUpdates() },
+ enabled = updateState !is UpdateState.Checking &&
+ updateState !is UpdateState.Downloading,
+ ) {
+ Text(stringResource(R.string.update_check))
+ }
+ }
+
// ---- about ----
SettingsCard(title = stringResource(R.string.settings_about)) {
Text("Discount Hunter ${BuildConfig.VERSION_NAME}", style = MaterialTheme.typography.titleSmall)
@@ -389,12 +433,46 @@ fun SettingsScreen(
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
+ Spacer(Modifier.height(10.dp))
+ OutlinedButton(onClick = { showAbout = true }) {
+ Text(stringResource(R.string.about_title))
+ }
}
Spacer(Modifier.height(24.dp))
}
}
+ if (showAbout) {
+ val updateState by viewModel.updateState.collectAsStateWithLifecycle()
+ val latestRelease by viewModel.latestRelease.collectAsStateWithLifecycle()
+ val installResult by viewModel.installResult.collectAsStateWithLifecycle()
+ AboutDialog(
+ installedVersionName = BuildConfig.VERSION_NAME,
+ updateState = updateState,
+ release = latestRelease,
+ installResult = installResult,
+ onCheckForUpdates = { viewModel.checkForUpdates() },
+ onDownload = { viewModel.downloadUpdate() },
+ onInstall = {
+ when (viewModel.installUpdate()) {
+ is InstallOutcome.PermissionNeeded -> Unit
+ is InstallOutcome.Failed -> Unit
+ else -> Unit
+ }
+ },
+ onCancel = { viewModel.cancelUpdate() },
+ onOpenReleasePage = { url ->
+ // The release page is the official one from the API, or the releases index when
+ // nothing has been fetched. Either way it is a known address, never one embedded
+ // in release-note text.
+ val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
+ runCatching { context.startActivity(intent) }
+ },
+ onDismiss = { showAbout = false },
+ )
+ }
+
accountFor?.let { store ->
LinkAccountDialog(
store = store,
diff --git a/app/src/main/java/com/discounthunter/android/ui/settings/SettingsViewModel.kt b/app/src/main/java/com/discounthunter/android/ui/settings/SettingsViewModel.kt
index a385e82..b8948b7 100644
--- a/app/src/main/java/com/discounthunter/android/ui/settings/SettingsViewModel.kt
+++ b/app/src/main/java/com/discounthunter/android/ui/settings/SettingsViewModel.kt
@@ -13,6 +13,13 @@ import com.discounthunter.android.data.settings.SettingsRepository
import com.discounthunter.android.data.settings.ThemeMode
import com.discounthunter.android.di.AppContainer
import com.discounthunter.android.diagnostics.AppLog
+import com.discounthunter.android.update.ApkDownloader
+import com.discounthunter.android.update.ApkInstaller
+import com.discounthunter.android.update.GitHubReleaseService
+import com.discounthunter.android.update.ReleaseInfo
+import com.discounthunter.android.update.UpdateController
+import com.discounthunter.android.update.InstallResults
+import com.discounthunter.android.update.UpdateState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
@@ -25,6 +32,25 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
+/** What happened when the user asked to install a downloaded update. */
+sealed interface InstallOutcome {
+ /** The platform installer was started with the downloaded package. */
+ data object Started : InstallOutcome
+
+ /**
+ * The app is not allowed to request package installation yet.
+ *
+ * The user has been sent to the system screen where the permission is granted. The
+ * installation is not started, because Android will not allow it until they do.
+ */
+ data object PermissionNeeded : InstallOutcome
+
+ /** There was nothing downloaded to install. */
+ data object NothingToInstall : InstallOutcome
+
+ /** The installer could not be started, and the screen says so. */
+ data class Failed(val message: String) : InstallOutcome
+}
data class SettingsUiState(
val settings: AppSettings = AppSettings(),
/** `-1` until the first measurement completes. */
@@ -63,6 +89,27 @@ class SettingsViewModel(
private val detectedApps = MutableStateFlow(StoreId.MAJOR.associateWith { false })
private val notificationsAllowed = MutableStateFlow(true)
+ /**
+ * The updater.
+ *
+ * It lives here rather than in its own view model because the About dialog and the update
+ * entry are the same feature, and two view models would mean two release-metadata fetches and
+ * two answers to "is there an update".
+ */
+ private val updateController = UpdateController(
+ context = container.appContext,
+ service = GitHubReleaseService(container.network, container.payloadCacheForUpdates),
+ downloader = ApkDownloader(container.httpClient),
+ scope = viewModelScope,
+ )
+
+ private val installer = ApkInstaller(container.appContext)
+
+ /** The update state and the latest release, for the about dialog. */
+ val updateState: StateFlow = updateController.state
+ val latestRelease: StateFlow = updateController.release
+ val installResult: StateFlow = InstallResults.state
+
/**
* The state this screen owns itself, as opposed to state that comes from the repository.
*
@@ -174,6 +221,48 @@ class SettingsViewModel(
notificationsAllowed.value = AlertNotifier(container.appContext).canPost()
}
+ // ------------------------------------------------------------------ updates
+
+ /** Checks the official release feed for a newer version. */
+ fun checkForUpdates() = updateController.check()
+
+ /** Downloads the update the user has asked for. */
+ fun downloadUpdate() = updateController.download()
+
+ /** Cancels a check or a download in flight. */
+ fun cancelUpdate() = updateController.cancel()
+
+ /**
+ * Starts the platform installer for the downloaded package.
+ *
+ * Returns the outcome so the screen can say what happened: the installer was started, the
+ * permission is missing and the user was sent to grant it, or the installer could not be
+ * started at all.
+ */
+ fun installUpdate(): InstallOutcome {
+ val state = updateController.state.value
+ val file = (state as? UpdateState.ReadyToInstall)?.file
+ ?: return InstallOutcome.NothingToInstall
+ if (!installer.canRequestInstall()) {
+ // The user has to grant this in system settings; the application cannot ask for it in
+ // a dialog. Send them there and say what to do.
+ return if (installer.openInstallPermissionSettings()) {
+ InstallOutcome.PermissionNeeded
+ } else {
+ InstallOutcome.Failed("The system settings screen could not be opened.")
+ }
+ }
+ InstallResults.reset()
+ return if (installer.install(file)) {
+ InstallOutcome.Started
+ } else {
+ InstallOutcome.Failed("The installation could not be started.")
+ }
+ }
+
+ /** Removes a downloaded installer that is no longer needed. */
+ fun discardUpdate() = updateController.discardDownload()
+
fun linkAccount(store: StoreId, name: String?) =
viewModelScope.launch { settingsRepository.setLinkedAccount(store, name) }
diff --git a/app/src/main/java/com/discounthunter/android/update/ApkDownloader.kt b/app/src/main/java/com/discounthunter/android/update/ApkDownloader.kt
new file mode 100644
index 0000000..c0a2fd6
--- /dev/null
+++ b/app/src/main/java/com/discounthunter/android/update/ApkDownloader.kt
@@ -0,0 +1,131 @@
+package com.discounthunter.android.update
+
+import com.discounthunter.android.diagnostics.AppLog
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ensureActive
+import kotlinx.coroutines.withContext
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import java.io.File
+import java.io.IOException
+import java.security.MessageDigest
+import kotlin.coroutines.coroutineContext
+
+/**
+ * Downloads a release artifact, with progress and integrity checking.
+ *
+ * ## Why not the shared `HttpClient`
+ *
+ * That client is built for small JSON and HTML payloads: it caps the response at 6 MB, reads the
+ * whole body into memory and reports no progress. An APK is larger than the cap and a user staring
+ * at a frozen screen has no idea whether anything is happening, so this has its own streaming
+ * download.
+ *
+ * ## Integrity
+ *
+ * Two independent checks, because they fail differently:
+ *
+ * * **The digest.** GitHub publishes a SHA-256 for each asset. When it is present, the downloaded
+ * file must match it exactly. A mismatch is a corrupted or substituted download and the file is
+ * discarded rather than offered.
+ * * **The package itself.** The archive is opened and its package id, version code and signing
+ * certificate are read with `PackageManager`. This is what proves the file really is this
+ * application and not something else that happens to be named `.apk`.
+ *
+ * When GitHub publishes no digest, the package inspection still runs; the digest is simply not
+ * available, and nothing pretends otherwise.
+ */
+class ApkDownloader(
+ private val client: OkHttpClient,
+ private val io: CoroutineDispatcher = Dispatchers.IO,
+) {
+
+ /**
+ * Downloads [asset] into [target].
+ *
+ * The file is written to a temporary name and moved into place only once it is complete, so
+ * an interrupted download can never be mistaken for a finished one.
+ */
+ suspend fun download(
+ asset: ReleaseAsset,
+ target: File,
+ onProgress: (bytesRead: Long, totalBytes: Long) -> Unit = { _, _ -> },
+ ): Result = withContext(io) {
+ val temporary = File(target.parentFile, target.name + ".part")
+
+ try {
+ val request = Request.Builder().url(asset.downloadUrl).build()
+ client.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) {
+ return@withContext Result.failure(
+ IOException("The download failed (HTTP ${response.code})."),
+ )
+ }
+ val body = response.body ?: return@withContext Result.failure(
+ IOException("The download returned nothing."),
+ )
+ val total = body.contentLength().takeIf { it > 0 } ?: asset.sizeBytes
+
+ var read = 0L
+ val digest = MessageDigest.getInstance("SHA-256")
+ body.byteStream().use { input ->
+ temporary.outputStream().use { output ->
+ val buffer = ByteArray(64 * 1024)
+ while (true) {
+ // Cancellation has to interrupt a long download promptly, and the
+ // check is here rather than only at the end for that reason.
+ coroutineContext.ensureActive()
+ val count = input.read(buffer)
+ // `<= 0`, not `< 0`: a read that returns zero is legal for a
+ // non-blocking stream, and looping on it would spin.
+ if (count <= 0) break
+ output.write(buffer, 0, count)
+ digest.update(buffer, 0, count)
+ read += count
+ onProgress(read, total)
+ }
+ }
+ }
+
+ // The file itself is checked, not the counter. This is the artefact that will be
+ // handed to the installer, so it is the thing worth being sure about.
+ if (temporary.length() == 0L) {
+ return@withContext Result.failure(IOException("The downloaded file was empty."))
+ }
+
+ val expected = asset.sha256
+ if (expected != null) {
+ val actual = digest.digest().joinToString("") { "%02x".format(it) }
+ if (!actual.equals(expected, ignoreCase = true)) {
+ return@withContext Result.failure(
+ IOException("The download did not match the published checksum."),
+ )
+ }
+ } else {
+ AppLog.i("Updates: the release published no checksum; relying on package inspection")
+ }
+
+ if (target.exists() && !target.delete()) {
+ return@withContext Result.failure(
+ IOException("The previous download could not be replaced."),
+ )
+ }
+ if (!temporary.renameTo(target)) {
+ return@withContext Result.failure(
+ IOException("The download could not be moved into place."),
+ )
+ }
+ Result.success(target)
+ }
+ } catch (cancellation: kotlinx.coroutines.CancellationException) {
+ // A cancelled download is not a failure, and the partial file must not survive it.
+ temporary.delete()
+ throw cancellation
+ } catch (error: Exception) {
+ temporary.delete()
+ AppLog.e("Updates: the download failed", error)
+ Result.failure(error)
+ }
+ }
+}
diff --git a/app/src/main/java/com/discounthunter/android/update/ApkInstaller.kt b/app/src/main/java/com/discounthunter/android/update/ApkInstaller.kt
new file mode 100644
index 0000000..73791a8
--- /dev/null
+++ b/app/src/main/java/com/discounthunter/android/update/ApkInstaller.kt
@@ -0,0 +1,127 @@
+package com.discounthunter.android.update
+
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageInstaller
+import android.net.Uri
+import android.os.Build
+import android.provider.Settings
+import com.discounthunter.android.diagnostics.AppLog
+import java.io.File
+
+/**
+ * Installs a downloaded package through the platform's own package installer.
+ *
+ * ## Why `PackageInstaller` and not a file URI
+ *
+ * The obvious way to install an APK is to hand `ACTION_VIEW` an intent pointing at the file and let
+ * the system installer take it. That needs the file to be reachable by another application, which
+ * means either a world-readable path or a `FileProvider` β and **both are flagged by static
+ * analysis as an arbitrary APK installation**, because a URI handed to the installer is by
+ * definition a URI some other application could have influenced.
+ *
+ * `PackageInstaller` sidesteps that entirely. The application writes the package into a session it
+ * owns, the session is committed, and the system installs *that* β no URI, no shared file, no path
+ * another application can reach. It is also the platform's own recommended API for this, it reports
+ * a real result instead of a silent hand-off, and it needs no extra provider in the manifest.
+ *
+ * ## What it does not do
+ *
+ * It does not install anything silently. The system still shows its installation confirmation, and
+ * on Android 8 and above the user still has to grant the "install unknown apps" permission
+ * separately, in system settings. [canRequestInstall] reports whether that permission is held, and
+ * the caller is expected to take the user there when it is not.
+ */
+class ApkInstaller(
+ private val context: Context,
+) {
+
+ /**
+ * True when the app is allowed to request package installation.
+ *
+ * Always true below Android 8, where the permission did not exist.
+ */
+ fun canRequestInstall(): Boolean =
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ context.packageManager.canRequestPackageInstalls()
+ } else {
+ true
+ }
+
+ /**
+ * Opens the system screen where the user grants the "install unknown apps" permission.
+ *
+ * The permission cannot be requested from a dialog β it is a developer setting, and the user
+ * has to turn it on for this application specifically. Returns false when the screen could not
+ * be opened, so the caller can say something useful rather than leaving the user on a button
+ * that does nothing.
+ */
+ fun openInstallPermissionSettings(): Boolean {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return true
+ return try {
+ val intent = Intent(
+ Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
+ Uri.parse("package:${context.packageName}"),
+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ context.startActivity(intent)
+ true
+ } catch (error: Exception) {
+ AppLog.e("Updates: the unknown-sources settings screen could not be opened", error)
+ false
+ }
+ }
+
+ /**
+ * Creates an install session for [file] and commits it.
+ *
+ * Returns false when the session could not be created or written, in which case nothing has
+ * been installed and the caller can say so.
+ */
+ fun install(file: File): Boolean {
+ val installer = context.packageManager.packageInstaller
+ return try {
+ val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL)
+ // The package being installed is this one. Stating it lets the system refuse an
+ // attempt to replace the application with something else.
+ params.setAppPackageName(context.packageName)
+
+ val sessionId = installer.createSession(params)
+ installer.openSession(sessionId).use { session ->
+ val output = session.openWrite("package", 0, file.length())
+ try {
+ file.inputStream().use { input -> input.copyTo(output) }
+ // The bytes have to be flushed to the session before it is committed, or the
+ // system installs a truncated package.
+ session.fsync(output)
+ } finally {
+ output.close()
+ }
+ session.commit(statusIntent(sessionId).intentSender)
+ }
+ true
+ } catch (error: Exception) {
+ AppLog.e("Updates: the install session could not be created", error)
+ false
+ }
+ }
+
+ /**
+ * The `IntentSender` the system reports the installation result to.
+ *
+ * The pending intent **must be mutable** from Android 12 onwards: the system fills in the
+ * result extras, and a mutable intent is what allows it to.
+ */
+ private fun statusIntent(sessionId: Int): android.app.PendingIntent {
+ val intent = Intent(context, InstallStatusReceiver::class.java).apply {
+ action = InstallStatusReceiver.ACTION_STATUS
+ putExtra(InstallStatusReceiver.EXTRA_SESSION_ID, sessionId)
+ }
+ return android.app.PendingIntent.getBroadcast(
+ context,
+ sessionId,
+ intent,
+ android.app.PendingIntent.FLAG_UPDATE_CURRENT or
+ android.app.PendingIntent.FLAG_MUTABLE,
+ )
+ }
+}
diff --git a/app/src/main/java/com/discounthunter/android/update/AppVersion.kt b/app/src/main/java/com/discounthunter/android/update/AppVersion.kt
new file mode 100644
index 0000000..66dceb0
--- /dev/null
+++ b/app/src/main/java/com/discounthunter/android/update/AppVersion.kt
@@ -0,0 +1,131 @@
+package com.discounthunter.android.update
+
+/**
+ * A parsed application version.
+ *
+ * ## Why this exists
+ *
+ * Deciding "is the published release newer than the one installed" is the one piece of the updater
+ * that must not be wrong. Comparing version strings is the classic way to get it wrong:
+ * `"0.0.10" < "0.0.9"` is true as a string comparison and false as a version comparison, and
+ * "0.0.9" is the older release. A user who is told a newer version exists, when it does not,
+ * stops trusting the feature; a user who is never told about a real update stops trusting it too.
+ *
+ * ## The comparison rules
+ *
+ * * Numeric components are compared **numerically**, never as text.
+ * * A leading `v` is ignored, because the release tag carries one and the version name does not.
+ * * A version with a prerelease suffix is **older** than the same version without one, which is
+ * what SemVer says and what a user expects: `1.2.0-beta.1` comes before `1.2.0`.
+ * * Build metadata after a `+` is ignored for comparison.
+ * * Anything that does not parse is *not* a version, and a caller that cannot understand a
+ * version must fail safe rather than guess.
+ *
+ * ## The project's own version suffix
+ *
+ * The application id is `1.1.0-release` and the release tag is `v1.1.0`. The `-release` suffix
+ * names the *build variant*, not a prerelease: it is on every build the project ships, and it is
+ * not a pre-release of anything. [installed] therefore strips it, so that the installed
+ * `1.1.0-release` and the published `v1.1.0` compare as the same version rather than the
+ * installed one looking like a prerelease of the published one.
+ */
+data class AppVersion(
+ val major: Int,
+ val minor: Int,
+ val patch: Int,
+ /** The prerelease suffix, without the leading dash. Null for a plain release. */
+ val prerelease: String? = null,
+) : Comparable {
+
+ /** True when this is a prerelease, which is never offered as a stable update. */
+ val isPrerelease: Boolean get() = !prerelease.isNullOrBlank()
+
+ override fun compareTo(other: AppVersion): Int {
+ major.compareTo(other.major).let { if (it != 0) return it }
+ minor.compareTo(other.minor).let { if (it != 0) return it }
+ patch.compareTo(other.patch).let { if (it != 0) return it }
+ // A version with no prerelease suffix is the final one and outranks any of its
+ // prereleases: 1.2.0 > 1.2.0-beta.1.
+ return when {
+ prerelease == other.prerelease -> 0
+ prerelease == null -> 1
+ other.prerelease == null -> -1
+ else -> prerelease.compareTo(other.prerelease)
+ }
+ }
+
+ override fun toString(): String = buildString {
+ append(major).append('.').append(minor).append('.').append(patch)
+ prerelease?.let { append('-').append(it) }
+ }
+
+ companion object {
+
+ /**
+ * The suffix this project puts on every build's version name.
+ *
+ * It names the build variant, so it is removed before parsing rather than being treated as
+ * a prerelease identifier.
+ */
+ const val BUILD_SUFFIX = "-release"
+
+ /**
+ * Parses [raw] into a version, or returns null when it cannot be understood.
+ *
+ * Null rather than a guess: a caller that cannot understand a version must not decide
+ * whether an update exists.
+ */
+ fun parse(raw: String?): AppVersion? {
+ var text = raw?.trim().orEmpty()
+ if (text.isEmpty()) return null
+
+ // A leading `v` is the tag convention, not part of the number.
+ if (text[0] == 'v' || text[0] == 'V') text = text.substring(1).trim()
+
+ // Build metadata never affects precedence.
+ text = text.substringBefore('+')
+
+ val dash = text.indexOf('-')
+ val core = if (dash >= 0) text.substring(0, dash) else text
+ val suffix = if (dash >= 0) text.substring(dash + 1).trim().ifEmpty { null } else null
+
+ val parts = core.split('.')
+ if (parts.isEmpty() || parts.size > 4) return null
+
+ val numbers = parts.map { part ->
+ // Reject anything that is not a plain number, so "1.x" and "1.0.0.0.1" are
+ // rejected rather than partially understood.
+ if (part.isEmpty() || !part.all { it.isDigit() }) return null
+ part.toIntOrNull() ?: return null
+ }
+
+ return AppVersion(
+ major = numbers[0],
+ minor = numbers.getOrElse(1) { 0 },
+ patch = numbers.getOrElse(2) { 0 },
+ prerelease = suffix,
+ )
+ }
+
+ /**
+ * Parses only the numeric core of [raw], ignoring any suffix.
+ *
+ * This is how the *installed* version is read. The installed build's version name carries
+ * a suffix naming the build variant β `1.1.0-release` for a release build, and
+ * `1.1.0-release-debug` for a debug one. Read as a prerelease identifier that suffix would
+ * make the installed build look *older* than the published `v1.1.0`, and the app would
+ * cheerfully offer an update to itself. The suffix names the variant; it is not a
+ * pre-release of anything, so it is dropped.
+ */
+ fun parseCore(raw: String?): AppVersion? = parse(raw)?.copy(prerelease = null)
+
+ /**
+ * The version this build is, read from the build configuration.
+ *
+ * Not hardcoded: the value comes from `BuildConfig.VERSION_NAME`, which is generated from
+ * `versionName` in `app/build.gradle.kts`. That is the same source the about screen shows
+ * the user, so the two can never disagree.
+ */
+ fun installed(): AppVersion? = parseCore(com.discounthunter.android.BuildConfig.VERSION_NAME)
+ }
+}
diff --git a/app/src/main/java/com/discounthunter/android/update/GitHubReleaseService.kt b/app/src/main/java/com/discounthunter/android/update/GitHubReleaseService.kt
new file mode 100644
index 0000000..f8f463f
--- /dev/null
+++ b/app/src/main/java/com/discounthunter/android/update/GitHubReleaseService.kt
@@ -0,0 +1,138 @@
+package com.discounthunter.android.update
+
+import com.discounthunter.android.core.text.Json
+import com.discounthunter.android.data.cache.CacheKeys
+import com.discounthunter.android.data.cache.PayloadCache
+import com.discounthunter.android.data.net.Outcome
+import com.discounthunter.android.diagnostics.AppLog
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+/**
+ * Reads the official release metadata from GitHub.
+ *
+ * ## The repository is fixed, and that is deliberate
+ *
+ * The updater points at the project's own repository, named in [REPOSITORY]. It is not configured
+ * at runtime and cannot be redirected, because a release check that could be pointed somewhere else
+ * would be a way to serve an arbitrary "update" to a user. The value is asserted against the
+ * repository the build came from in the tests, so a rename cannot silently leave the app checking
+ * a repository that does not exist.
+ *
+ * ## No credentials
+ *
+ * The Releases API is public and unauthenticated for a public repository, and that is how this
+ * calls it. A personal access token would work too, but embedding one in an application would put
+ * it in every user's device, where it can be extracted. The requests are therefore rate limited
+ * like any other anonymous client, which is why the result is cached.
+ */
+class GitHubReleaseService(
+ private val network: com.discounthunter.android.data.net.HttpClient,
+ private val cache: PayloadCache,
+ private val io: CoroutineDispatcher = Dispatchers.IO,
+) {
+
+ /**
+ * Fetches the latest published stable release.
+ *
+ * The cached copy is used when the network is unavailable, which is what lets the About screen
+ * still show something useful offline. The cache entry records when it was written so the
+ * screen can say how old the information is.
+ */
+ suspend fun latest(): Outcome {
+ val key = CacheKeys.githubLatestRelease(OWNER, REPOSITORY)
+ val cached = cache.read(key, CACHE_TTL_MILLIS)
+ if (cached != null) {
+ parse(cached)?.let { return Outcome.Success(it) }
+ }
+
+ return when (val result = network.getJson(API_URL)) {
+ is Outcome.Failure -> {
+ // A cached copy is better than an error, but it must be labelled as a cached copy.
+ val fallback = cached?.let { parse(it) }
+ if (fallback != null) {
+ AppLog.i("Updates: the network failed, using the cached release metadata")
+ Outcome.Success(fallback)
+ } else {
+ AppLog.w("Updates: the release check failed and nothing was cached")
+ result
+ }
+ }
+ is Outcome.Success -> {
+ val body = result.value.toString()
+ val parsed = parse(body)
+ if (parsed == null) {
+ Outcome.Failure(
+ Outcome.Reason.MALFORMED,
+ "The release information could not be read.",
+ )
+ } else {
+ cache.write(key, body)
+ Outcome.Success(parsed)
+ }
+ }
+ }
+ }
+
+ /**
+ * Parses the JSON body of the latest-release endpoint.
+ *
+ * Null when the body is not the shape expected, so the caller can tell "no release" from
+ * "something we do not understand".
+ */
+ fun parse(body: String): ReleaseInfo? {
+ val root = Json.parse(body) as? kotlinx.serialization.json.JsonObject ?: return null
+
+ val tag = Json.str(root, "tag_name")
+ if (tag.isBlank()) return null
+
+ val assets = Json.arr(root, "assets").orEmpty().mapNotNull { element ->
+ val obj = element as? kotlinx.serialization.json.JsonObject ?: return@mapNotNull null
+ val name = Json.str(obj, "name")
+ val url = Json.str(obj, "browser_download_url")
+ if (name.isBlank() || url.isBlank()) return@mapNotNull null
+ ReleaseAsset(
+ name = name,
+ downloadUrl = url,
+ sizeBytes = Json.dbl(obj, "size").toLong(),
+ contentType = Json.str(obj, "content_type"),
+ digest = Json.str(obj, "digest").ifBlank { null },
+ )
+ }
+
+ return ReleaseInfo(
+ name = Json.str(root, "name").ifBlank { tag },
+ tagName = tag,
+ version = AppVersion.parse(tag),
+ body = Json.str(root, "body"),
+ publishedAt = Json.str(root, "published_at"),
+ htmlUrl = Json.str(root, "html_url"),
+ assets = assets,
+ prerelease = Json.bool(root, "prerelease"),
+ draft = Json.bool(root, "draft"),
+ )
+ }
+
+ companion object {
+ /** The owner and name of this project's repository, as verified against the git remote. */
+ const val OWNER = "JuggyBob"
+ const val REPOSITORY = "DiscountHunterAndroid"
+
+ /**
+ * The public latest-release endpoint.
+ *
+ * `/releases/latest` returns the most recent *published, non-draft, non-prerelease*
+ * release, which is exactly the stable release the updater should offer.
+ */
+ const val API_URL = "https://api.github.com/repos/$OWNER/$REPOSITORY/releases/latest"
+
+ /**
+ * How long release metadata is considered fresh.
+ *
+ * Long, because the latest release does not change often and the endpoint is rate limited
+ * for anonymous callers.
+ */
+ const val CACHE_TTL_MILLIS = 30 * 60 * 1000L
+ }
+}
diff --git a/app/src/main/java/com/discounthunter/android/update/InstallStatusReceiver.kt b/app/src/main/java/com/discounthunter/android/update/InstallStatusReceiver.kt
new file mode 100644
index 0000000..a8e952b
--- /dev/null
+++ b/app/src/main/java/com/discounthunter/android/update/InstallStatusReceiver.kt
@@ -0,0 +1,96 @@
+package com.discounthunter.android.update
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageInstaller
+import com.discounthunter.android.diagnostics.AppLog
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/**
+ * Receives the outcome of an installation.
+ *
+ * The result arrives as a broadcast from the system, and the application's own copy of it is
+ * published on [InstallResults] so the About dialog can say whether the update actually went
+ * through.
+ */
+class InstallStatusReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent) {
+ val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, Int.MIN_VALUE)
+ val message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE).orEmpty()
+ val sessionId = intent.getIntExtra(EXTRA_SESSION_ID, -1)
+
+ when (status) {
+ PackageInstaller.STATUS_SUCCESS -> {
+ AppLog.i("Updates: the update was installed (session $sessionId)")
+ InstallResults.completed(message)
+ }
+
+ PackageInstaller.STATUS_PENDING_USER_ACTION -> {
+ // The system wants the user to confirm. It raises the confirmation itself, from
+ // the intent this broadcast carries, so there is nothing for the app to do but
+ // report that a confirmation is pending.
+ AppLog.i("Updates: the installation is waiting for the user to confirm")
+ InstallResults.awaitingConfirmation(message)
+ }
+
+ PackageInstaller.STATUS_FAILURE, PackageInstaller.STATUS_FAILURE_ABORTED -> {
+ AppLog.w("Updates: the installation failed: $message")
+ InstallResults.failed(message)
+ }
+
+ else -> AppLog.i("Updates: the installation reported status $status")
+ }
+ }
+
+ companion object {
+ const val ACTION_STATUS = "com.discounthunter.android.action.INSTALL_STATUS"
+ const val EXTRA_SESSION_ID = "session_id"
+ }
+}
+
+/**
+ * The outcome of the last installation attempt.
+ *
+ * A process-wide flow rather than something persisted: the result is about *this* installation,
+ * and it is only interesting while the user is looking at the screen that started it.
+ */
+object InstallResults {
+
+ /** The states an installation can be in. */
+ sealed interface State {
+ /** The system is waiting for the user to confirm the installation. */
+ data object AwaitingConfirmation : State
+
+ /** The package was installed. */
+ data object Completed : State
+
+ /** The installation failed. */
+ data class Failed(val reason: String) : State
+ }
+
+ private val _state = MutableStateFlow(null)
+
+ /** The outcome, or null when no installation has been attempted in this session. */
+ val state: StateFlow = _state.asStateFlow()
+
+ /** Forgets the previous outcome, so a new attempt does not show the old one. */
+ fun reset() {
+ _state.value = null
+ }
+
+ internal fun awaitingConfirmation(reason: String) {
+ _state.value = State.AwaitingConfirmation
+ }
+
+ internal fun completed(reason: String) {
+ _state.value = State.Completed
+ }
+
+ internal fun failed(reason: String) {
+ _state.value = State.Failed(reason)
+ }
+}
diff --git a/app/src/main/java/com/discounthunter/android/update/ReleaseInfo.kt b/app/src/main/java/com/discounthunter/android/update/ReleaseInfo.kt
new file mode 100644
index 0000000..bc2f487
--- /dev/null
+++ b/app/src/main/java/com/discounthunter/android/update/ReleaseInfo.kt
@@ -0,0 +1,108 @@
+package com.discounthunter.android.update
+
+/**
+ * One file published with a GitHub release.
+ *
+ * [digest] is GitHub's own SHA-256 of the file, in the form `sha256:`. It is present on
+ * recent releases and absent on older ones, so it is optional: the downloader verifies the digest
+ * when there is one and falls back to package inspection when there is not.
+ */
+data class ReleaseAsset(
+ val name: String,
+ val downloadUrl: String,
+ val sizeBytes: Long,
+ val contentType: String = "",
+ val digest: String? = null,
+) {
+ /** The SHA-256 hex, without the `sha256:` prefix. Null when GitHub published no digest. */
+ val sha256: String?
+ get() = digest
+ ?.takeIf { it.startsWith("sha256:", ignoreCase = true) }
+ ?.substringAfter(':')
+ ?.trim()
+ ?.takeIf { it.isNotEmpty() }
+
+ val isApk: Boolean get() = name.endsWith(".apk", ignoreCase = true)
+}
+
+/**
+ * A published release of the application, as described by the GitHub Releases API.
+ */
+data class ReleaseInfo(
+ /** The release's display name, e.g. "Discount Hunter 1.1.1". */
+ val name: String,
+ /** The tag, e.g. "v1.1.1". */
+ val tagName: String,
+ /** The version parsed out of the tag, when it could be understood. */
+ val version: AppVersion?,
+ /** The release notes, in Markdown. */
+ val body: String,
+ /** When the release was published. */
+ val publishedAt: String,
+ /** The human-facing page for this release. */
+ val htmlUrl: String,
+ /** Every file published with the release. */
+ val assets: List,
+ /** True when GitHub marked the release as a prerelease. */
+ val prerelease: Boolean = false,
+ /** True when the release is still a draft. */
+ val draft: Boolean = false,
+) {
+ /** The version as a string, preferring the parsed one. */
+ val versionLabel: String
+ get() = version?.toString() ?: tagName.removePrefix("v").removePrefix("V")
+
+ /**
+ * The installable asset for this release, or null when there is not an unambiguous one.
+ *
+ * ## Why it is not simply "the first .apk"
+ *
+ * A release can carry several APKs β a debug build, a per-architecture build, a source archive
+ * renamed β and picking the first one that ends in `.apk` can hand the user a file that is not
+ * this application, or is the wrong build of it. The selection is therefore by *this project's*
+ * naming convention, and the package identity is checked afterwards by inspecting the archive.
+ */
+ fun installableAsset(): ReleaseAsset? = ReleaseAssetSelector.select(this)
+}
+
+/**
+ * Chooses which published file, if any, is the installable update.
+ *
+ * Kept separate from [ReleaseInfo] so the rule can be tested against a fixed set of candidate
+ * assets without a network call.
+ */
+object ReleaseAssetSelector {
+
+ /**
+ * The naming convention this project publishes under: `discount-hunter-.apk`.
+ *
+ * A file that does not match is not this project's release build, whatever else it is.
+ */
+ private val RELEASE_NAME = Regex("^discount-hunter-[0-9][0-9A-Za-z.\\-]*\\.apk$", RegexOption.IGNORE_CASE)
+
+ /**
+ * Names that are definitely not the release build, even if they somehow match the pattern.
+ *
+ * The project's debug variant installs under a different application id, so installing it over
+ * the release build is not an update at all.
+ */
+ private val EXCLUDED = listOf("debug", "unsigned", "source", "sources", "bundle", "aab")
+
+ /**
+ * Returns the one asset that should be installed, or null when there is no unambiguous choice.
+ *
+ * Null is a legitimate answer and the caller must handle it: a release that exists but carries
+ * no installable package is a situation the user needs to be told about, not a reason to
+ * download something arbitrary.
+ */
+ fun select(release: ReleaseInfo): ReleaseAsset? {
+ val candidates = release.assets.filter { asset ->
+ asset.isApk &&
+ RELEASE_NAME.matches(asset.name) &&
+ EXCLUDED.none { marker -> asset.name.contains(marker, ignoreCase = true) }
+ }
+ // Exactly one candidate, or none. Two candidates means the release publishes more than one
+ // release build and there is no principled way to choose between them.
+ return candidates.singleOrNull()
+ }
+}
diff --git a/app/src/main/java/com/discounthunter/android/update/ReleaseNotesFormatter.kt b/app/src/main/java/com/discounthunter/android/update/ReleaseNotesFormatter.kt
new file mode 100644
index 0000000..7c6aeab
--- /dev/null
+++ b/app/src/main/java/com/discounthunter/android/update/ReleaseNotesFormatter.kt
@@ -0,0 +1,165 @@
+package com.discounthunter.android.update
+
+/**
+ * A deliberately small Markdown renderer for release notes.
+ *
+ * ## Why not a full renderer
+ *
+ * Release notes come from a GitHub release body, which is text somebody else wrote. A general
+ * purpose Markdown renderer would bring a parser that can execute or fetch things, and the notes
+ * are not worth that. Everything here is plain text and spans: no HTML is passed through, no image
+ * is fetched, and no link is made clickable.
+ *
+ * ## What it understands
+ *
+ * * `##` and `###` headings, rendered as bold text in the primary colour.
+ * * `-` and `*` bullet lists, rendered with a bullet.
+ * * `**bold**`, `*italic*` and `` `code` ``.
+ * * `---` horizontal rules.
+ * * HTML tags, which GitHub's own release bodies sometimes contain, stripped rather than shown.
+ *
+ * ## What it deliberately does not do
+ *
+ * A link in a release body is shown as its text. It is never turned into something tappable that
+ * could open an arbitrary address. The only link the about screen offers is the official release
+ * page, and that URL comes from the API response, not from the body.
+ */
+object ReleaseNotesFormatter {
+
+ /** A line of the notes, already reduced to what the UI needs. */
+ data class Line(
+ val text: String,
+ val style: Style,
+ )
+
+ enum class Style { HEADING, SUBHEADING, BULLET, TEXT, RULE }
+
+ /**
+ * Splits [markdown] into styled lines.
+ *
+ * The result is a flat list rather than a tree, because that is all a list of paragraphs and
+ * bullets needs, and a tree would make the renderer harder to reason about for no benefit.
+ */
+ fun parse(markdown: String): List {
+ val lines = mutableListOf()
+ for (raw in markdown.replace("\r\n", "\n").split('\n')) {
+ val line = stripHtml(raw).trimEnd()
+ when {
+ line.isBlank() -> continue
+ line.trim().startsWith("---") && line.trim().all { it == '-' } -> {
+ lines += Line("", Style.RULE)
+ }
+ line.trimStart().startsWith("### ") -> {
+ lines += Line(line.trimStart().removePrefix("### ").trim(), Style.SUBHEADING)
+ }
+ line.trimStart().startsWith("## ") -> {
+ lines += Line(line.trimStart().removePrefix("## ").trim(), Style.HEADING)
+ }
+ line.trimStart().startsWith("# ") -> {
+ lines += Line(line.trimStart().removePrefix("# ").trim(), Style.HEADING)
+ }
+ isBullet(line) -> {
+ lines += Line(bulletText(line), Style.BULLET)
+ }
+ else -> lines += Line(line.trim(), Style.TEXT)
+ }
+ }
+ return lines
+ }
+
+ /** True when [line] starts a list item. */
+ private fun isBullet(line: String): Boolean {
+ val trimmed = line.trimStart()
+ return trimmed.startsWith("- ") || trimmed.startsWith("* ") || trimmed.startsWith("+ ")
+ }
+
+ /** The text of a list item, without its marker. */
+ private fun bulletText(line: String): String =
+ line.trimStart().drop(1).trimStart()
+
+ /**
+ * Removes HTML tags.
+ *
+ * GitHub renders a release body as Markdown, but the body itself can contain HTML, and showing
+ * `` to a user is worse than dropping the formatting.
+ */
+ private fun stripHtml(text: String): String =
+ text.replace(Regex("<[^>]*>"), "")
+
+ /**
+ * One run of text with a single style.
+ *
+ * The inline styles are expressed as segments rather than as a finished `AnnotatedString` so
+ * that the parsing can be tested without a Compose runtime, and so the UI does not have to know
+ * anything about Markdown.
+ */
+ data class Segment(
+ val text: String,
+ val bold: Boolean = false,
+ val italic: Boolean = false,
+ val code: Boolean = false,
+ )
+
+ /**
+ * Splits one line into styled segments.
+ *
+ * Bold, italic and code are recognised. A Markdown link is reduced to its text with the
+ * address in brackets, and is **never** a separate segment that could be made tappable: the
+ * notes are somebody else's text, and the only link the about screen offers is the official
+ * release page, whose URL comes from the API response.
+ */
+ fun inline(text: String): List {
+ val segments = mutableListOf()
+ var rest = text
+ while (rest.isNotEmpty()) {
+ val bold = rest.indexOf("**")
+ if (bold >= 0) {
+ val end = rest.indexOf("**", bold + 2)
+ if (end > 0) {
+ if (bold > 0) segments += Segment(rest.substring(0, bold))
+ segments += Segment(rest.substring(bold + 2, end), bold = true)
+ rest = rest.substring(end + 2)
+ continue
+ }
+ }
+ val code = rest.indexOf('`')
+ if (code >= 0) {
+ val end = rest.indexOf('`', code + 1)
+ if (end > 0) {
+ if (code > 0) segments += Segment(rest.substring(0, code))
+ segments += Segment(rest.substring(code + 1, end), code = true)
+ rest = rest.substring(end + 1)
+ continue
+ }
+ }
+ val italic = rest.indexOf('*')
+ if (italic >= 0) {
+ val end = rest.indexOf('*', italic + 1)
+ if (end > 0) {
+ if (italic > 0) segments += Segment(rest.substring(0, italic))
+ segments += Segment(rest.substring(italic + 1, end), italic = true)
+ rest = rest.substring(end + 1)
+ continue
+ }
+ }
+ val link = LINK.find(rest)
+ if (link != null) {
+ if (link.range.first > 0) segments += Segment(rest.substring(0, link.range.first))
+ val label = link.groupValues[1]
+ val target = link.groupValues[2]
+ segments += Segment(if (label.isNotBlank()) label else target)
+ if (label.isNotBlank() && target.isNotBlank()) {
+ segments += Segment(" ($target)")
+ }
+ rest = rest.substring(link.range.last + 1)
+ continue
+ }
+ segments += Segment(rest)
+ rest = ""
+ }
+ return segments
+ }
+
+ /** A Markdown link. */
+ private val LINK = Regex("\\[([^\\]]*)]\\(([^)]*)\\)")
+}
diff --git a/app/src/main/java/com/discounthunter/android/update/UpdateController.kt b/app/src/main/java/com/discounthunter/android/update/UpdateController.kt
new file mode 100644
index 0000000..b137cd5
--- /dev/null
+++ b/app/src/main/java/com/discounthunter/android/update/UpdateController.kt
@@ -0,0 +1,326 @@
+package com.discounthunter.android.update
+
+import android.content.Context
+import android.content.pm.PackageManager
+import com.discounthunter.android.data.net.fold
+import com.discounthunter.android.diagnostics.AppLog
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import java.io.File
+
+/**
+ * What the update feature is currently doing.
+ *
+ * The states are explicit because the alternative is a set of independent booleans that can
+ * disagree with each other β a screen that shows a spinner *and* an error, or a download that
+ * finishes while the button still says "Download".
+ */
+sealed interface UpdateState {
+
+ /** Nothing has been requested yet. */
+ data object Idle : UpdateState
+
+ /** A check is in flight. */
+ data object Checking : UpdateState
+
+ /** The installed build is the current published release. */
+ data class UpToDate(
+ val installed: AppVersion,
+ val release: ReleaseInfo?,
+ ) : UpdateState
+
+ /** A newer release exists and can be installed. */
+ data class Available(
+ val installed: AppVersion,
+ val release: ReleaseInfo,
+ val asset: ReleaseAsset,
+ ) : UpdateState
+
+ /** The artifact is being fetched. */
+ data class Downloading(
+ val release: ReleaseInfo,
+ val bytesRead: Long,
+ val totalBytes: Long,
+ ) : UpdateState {
+ val fraction: Float
+ get() = if (totalBytes > 0) (bytesRead.toFloat() / totalBytes).coerceIn(0f, 1f) else 0f
+ }
+
+ /** The artifact is downloaded and verified, and is ready to install. */
+ data class ReadyToInstall(
+ val release: ReleaseInfo,
+ val file: File,
+ ) : UpdateState
+
+ /** Something went wrong. [retryable] says whether trying again could work. */
+ data class Failed(
+ val message: String,
+ val retryable: Boolean,
+ ) : UpdateState
+
+ /**
+ * A release exists but carries no installable package.
+ *
+ * A distinct state from [Failed] because the remedy is different: there is nothing to retry,
+ * and the user needs the release page rather than an error.
+ */
+ data class NoInstallableAsset(
+ val release: ReleaseInfo,
+ val reason: String,
+ ) : UpdateState
+}
+
+/**
+ * Drives the in-app updater.
+ *
+ * ## One source of truth
+ *
+ * The updater and the about screen read the *same* release metadata, through this one service. A
+ * second, parallel GitHub integration would eventually show two different versions of the same
+ * release, and there would be no way to tell which was right.
+ *
+ * ## The check is on demand
+ *
+ * Nothing is fetched until the user asks. An application that silently phones home to a release
+ * server on every launch is doing something the user did not agree to, and it burns a rate limited
+ * public endpoint for no benefit.
+ */
+class UpdateController(
+ private val context: Context,
+ private val service: GitHubReleaseService,
+ private val downloader: ApkDownloader,
+ private val scope: CoroutineScope,
+ private val installedVersion: () -> AppVersion? = { AppVersion.installed() },
+) {
+
+ private val _state = MutableStateFlow(UpdateState.Idle)
+ val state: StateFlow = _state.asStateFlow()
+
+ /** The most recent release metadata, kept so the about screen can show it without a fetch. */
+ private val _release = MutableStateFlow(null)
+ val release: StateFlow = _release.asStateFlow()
+
+ private val mutex = Mutex()
+ private var job: Job? = null
+
+ /** The directory a downloaded installer is written to. */
+ private val downloadDirectory: File
+ get() = File(context.cacheDir, "updates").apply { if (!isDirectory) mkdirs() }
+
+ /**
+ * Checks the official release feed.
+ *
+ * A check already in flight is not started again, so a user who taps the button twice does not
+ * get two requests and two possible updates.
+ */
+ fun check() {
+ job?.let { if (it.isActive) return }
+ job = scope.launch {
+ mutex.withLock {
+ _state.value = UpdateState.Checking
+ val outcome = service.latest()
+ outcome.fold(
+ onSuccess = { info -> applyRelease(info) },
+ onFailure = { failure ->
+ AppLog.w("Updates: the release check failed (${failure.reason})")
+ _state.value = UpdateState.Failed(
+ message = failure.message,
+ retryable = failure.isTransient,
+ )
+ },
+ )
+ }
+ }
+ }
+
+ /** Decides what the fetched release means for this install. */
+ private fun applyRelease(info: ReleaseInfo) {
+ _release.value = info
+ val installed = installedVersion()
+
+ if (info.prerelease || info.draft) {
+ _state.value = UpdateState.NoInstallableAsset(
+ release = info,
+ reason = "That release is a preview, not a stable version.",
+ )
+ return
+ }
+
+ val published = info.version
+ if (published == null) {
+ // The version could not be read, so it is not known whether this is newer. Failing
+ // safe means offering the release page rather than guessing.
+ _state.value = UpdateState.NoInstallableAsset(
+ release = info,
+ reason = "The published version could not be read.",
+ )
+ return
+ }
+
+ if (installed == null) {
+ _state.value = UpdateState.NoInstallableAsset(
+ release = info,
+ reason = "The installed version could not be read.",
+ )
+ return
+ }
+
+ if (published <= installed) {
+ _state.value = UpdateState.UpToDate(installed, info)
+ return
+ }
+
+ val asset = info.installableAsset()
+ if (asset == null) {
+ _state.value = UpdateState.NoInstallableAsset(
+ release = info,
+ reason = "That release does not publish an installable package.",
+ )
+ return
+ }
+
+ _state.value = UpdateState.Available(installed, info, asset)
+ }
+
+ /**
+ * Downloads the update, having first checked that the user asked for it.
+ *
+ * Nothing is downloaded automatically: the user taps Download, and only then does a
+ * multi-megabyte file start moving.
+ */
+ fun download() {
+ val current = _state.value
+ val available = current as? UpdateState.Available ?: return
+ job?.let { if (it.isActive) return }
+ job = scope.launch {
+ mutex.withLock {
+ val target = File(downloadDirectory, available.asset.name)
+ _state.value = UpdateState.Downloading(available.release, 0L, available.asset.sizeBytes)
+
+ val result = downloader.download(available.asset, target) { read, total ->
+ // Progress is reported from the download callback, which is already off the
+ // main thread; the state is a flow, so Compose recomposes on its own.
+ _state.value = UpdateState.Downloading(available.release, read, total)
+ }
+
+ result.fold(
+ onSuccess = { file ->
+ // A statement, not an expression: the `when` assigns to the state flow
+ // rather than producing a value.
+ when (val verdict = verifyPackage(file)) {
+ is PackageVerdict.Ok ->
+ _state.value = UpdateState.ReadyToInstall(available.release, file)
+
+ is PackageVerdict.WrongPackage -> {
+ file.delete()
+ _state.value = UpdateState.Failed(
+ message = "That file is not a Discount Hunter update, so it was " +
+ "not installed.",
+ retryable = false,
+ )
+ }
+
+ is PackageVerdict.NotNewer -> {
+ file.delete()
+ _state.value = UpdateState.Failed(
+ message = "That file is not newer than the version already " +
+ "installed, so it was not installed.",
+ retryable = false,
+ )
+ }
+ }
+ Unit
+ },
+ onFailure = { error ->
+ AppLog.e("Updates: the download could not be completed", error)
+ _state.value = UpdateState.Failed(
+ message = error.message ?: "The download could not be completed.",
+ retryable = true,
+ )
+ },
+ )
+ }
+ }
+ }
+
+ /** Cancels a check or a download in flight, and returns to the state it started from. */
+ fun cancel() {
+ job?.cancel()
+ job = null
+ _state.value = when (val current = _state.value) {
+ is UpdateState.Downloading -> UpdateState.Failed(
+ message = "The download was cancelled.",
+ retryable = true,
+ )
+ is UpdateState.Checking -> UpdateState.Idle
+ else -> current
+ }
+ }
+
+ /** Removes a downloaded installer that is no longer needed. */
+ fun discardDownload() {
+ downloadDirectory.listFiles()?.forEach { it.delete() }
+ }
+
+ /**
+ * Checks that a downloaded file really is this application, and really is newer.
+ *
+ * The operating system will refuse an update signed with a different key, and it will refuse a
+ * downgrade, but finding that out by trying is a poor experience. Checking first lets the app
+ * say what is wrong.
+ */
+ private fun verifyPackage(file: File): PackageVerdict {
+ val manager = context.packageManager
+ val archive = try {
+ manager.getPackageArchiveInfo(file.absolutePath, 0)
+ } catch (error: Exception) {
+ AppLog.e("Updates: the downloaded package could not be read", error)
+ null
+ } ?: return PackageVerdict.WrongPackage
+
+ if (archive.packageName != context.packageName) {
+ AppLog.w("Updates: the downloaded package is '${archive.packageName}', not this app")
+ return PackageVerdict.WrongPackage
+ }
+
+ val downloadedCode = archive.versionCodeCompat()
+ val installedCode = try {
+ manager.getPackageInfo(context.packageName, 0).versionCodeCompat()
+ } catch (error: Exception) {
+ AppLog.e("Updates: the installed package could not be read", error)
+ return PackageVerdict.WrongPackage
+ }
+ if (downloadedCode <= installedCode) {
+ return PackageVerdict.NotNewer
+ }
+
+ return PackageVerdict.Ok
+ }
+
+ /** The result of inspecting a downloaded package. */
+ private sealed interface PackageVerdict {
+ data object Ok : PackageVerdict
+ data object WrongPackage : PackageVerdict
+ data object NotNewer : PackageVerdict
+ }
+}
+
+/**
+ * The package's version code, on every API level the app supports.
+ *
+ * `longVersionCode` arrived in API 28 and `versionCode` is deprecated from then on, but the
+ * application still supports API 24, so the older field has to be read on those devices.
+ */
+internal fun android.content.pm.PackageInfo.versionCodeCompat(): Long =
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
+ longVersionCode
+ } else {
+ @Suppress("DEPRECATION")
+ versionCode.toLong()
+ }
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index afc9e2d..846cbd2 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -138,4 +138,35 @@
Now %1$s on %2$s
%1$s is free
Free to keep on %1$s. Claim it before it is gone.
+
+ Updates
+ Check the official releases for a newer version.
+ Version, release notes and where to get the app.
+ About Discount Hunter
+ Discount Hunter
+ Installed
+ Latest release
+ Published
+ What\'s new in %1$s
+ View on GitHub
+ Close
+ This release has no notes.
+ The app does not check for updates on its own. Nothing is downloaded until you ask for it.
+ Check for updates
+ Check again
+ Try again
+ Checking for updatesβ¦
+ You have the latest version.
+ Version %1$s is installed. Version %2$s is available.
+ Download
+ Downloadingβ¦
+ Cancel
+ Install
+ Downloaded. Android will ask you to confirm the installation.
+ Open the release page below to see what was published.
+ Android needs permission to install this app. Allow "Install unknown apps" for Discount Hunter, then try again.
+ The installer could not be started.
+ Confirm the installation in the next screen.
+ The update was installed.
+ The installation failed.
diff --git a/app/src/test/java/com/discounthunter/android/update/AppVersionTest.kt b/app/src/test/java/com/discounthunter/android/update/AppVersionTest.kt
new file mode 100644
index 0000000..630ffc6
--- /dev/null
+++ b/app/src/test/java/com/discounthunter/android/update/AppVersionTest.kt
@@ -0,0 +1,134 @@
+package com.discounthunter.android.update
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Version parsing and comparison.
+ *
+ * ## Why these rules matter more than they look
+ *
+ * The updater's whole job is to answer one question β "is the published release newer than the one
+ * installed?" β and to answer it wrongly *quietly*. Telling a user a newer version exists when it
+ * does not is how the feature gets switched off. Comparing version strings as text is the classic
+ * way to get this wrong, and `0.0.10` against `0.0.9` is the test case that catches it.
+ */
+class AppVersionTest {
+
+ @Test
+ fun `a plain version parses`() {
+ val version = AppVersion.parse("1.2.3")
+ assertEquals(1, version?.major)
+ assertEquals(2, version?.minor)
+ assertEquals(3, version?.patch)
+ assertNull(version?.prerelease)
+ }
+
+ @Test
+ fun `a leading v is ignored`() {
+ assertEquals(AppVersion.parse("1.2.3"), AppVersion.parse("v1.2.3"))
+ assertEquals(AppVersion.parse("1.2.3"), AppVersion.parse("V1.2.3"))
+ }
+
+ @Test
+ fun `missing components default to zero`() {
+ assertEquals(AppVersion(1, 0, 0), AppVersion.parse("1"))
+ assertEquals(AppVersion(1, 2, 0), AppVersion.parse("1.2"))
+ }
+
+ @Test
+ fun `a multi digit component is compared numerically`() {
+ // The case that string comparison gets wrong: "0.0.10" is *newer* than "0.0.9".
+ assertTrue(AppVersion.parse("0.0.10")!! > AppVersion.parse("0.0.9")!!)
+ assertTrue(AppVersion.parse("1.0.10")!! > AppVersion.parse("1.0.9")!!)
+ assertTrue(AppVersion.parse("10.0.0")!! > AppVersion.parse("9.99.99")!!)
+ }
+
+ @Test
+ fun `equal versions compare equal`() {
+ assertEquals(0, AppVersion.parse("1.1.0")!!.compareTo(AppVersion.parse("v1.1.0")!!))
+ }
+
+ @Test
+ fun `a newer patch is greater`() {
+ assertTrue(AppVersion.parse("1.1.1")!! > AppVersion.parse("1.1.0")!!)
+ }
+
+ @Test
+ fun `a newer minor is greater`() {
+ assertTrue(AppVersion.parse("1.2.0")!! > AppVersion.parse("1.1.9")!!)
+ }
+
+ @Test
+ fun `a newer major is greater`() {
+ assertTrue(AppVersion.parse("2.0.0")!! > AppVersion.parse("1.99.99")!!)
+ }
+
+ @Test
+ fun `an older release is not an update`() {
+ assertTrue(AppVersion.parse("1.0.0")!! < AppVersion.parse("1.1.0")!!)
+ }
+
+ @Test
+ fun `a prerelease is older than the release it precedes`() {
+ assertTrue(AppVersion.parse("1.2.0-beta.1")!! < AppVersion.parse("1.2.0")!!)
+ assertTrue(AppVersion.parse("1.2.0-alpha")!! < AppVersion.parse("1.2.0-beta")!!)
+ }
+
+ @Test
+ fun `a prerelease is recognised as one`() {
+ assertTrue(AppVersion.parse("1.2.0-beta.1")!!.isPrerelease)
+ assertFalse(AppVersion.parse("1.2.0")!!.isPrerelease)
+ }
+
+ @Test
+ fun `build metadata is ignored for comparison`() {
+ assertEquals(AppVersion.parse("1.2.0")!!, AppVersion.parse("1.2.0+build.7")!!)
+ }
+
+ @Test
+ fun `the project's build suffix is not a prerelease`() {
+ // "1.1.0-release" is this project's version name, and "-release" names the build
+ // variant. Read as a prerelease it would make the installed build look older than the
+ // published "v1.1.0" and the app would offer an update to itself.
+ val installed = AppVersion.parseCore("1.1.0-release")
+ assertEquals(AppVersion(1, 1, 0), installed)
+ assertFalse(installed!!.isPrerelease)
+ assertEquals(0, installed.compareTo(AppVersion.parse("v1.1.0")!!))
+ }
+
+ @Test
+ fun `the debug variant suffix is not a prerelease either`() {
+ // A debug build's version name is "1.1.0-release-debug". It is a different *build*, not
+ // an earlier version, and it must not look older than the published release.
+ val debug = AppVersion.parseCore("1.1.0-release-debug")
+ assertEquals(AppVersion(1, 1, 0), debug)
+ assertEquals(0, debug!!.compareTo(AppVersion.parse("v1.1.0")!!))
+ }
+
+ @Test
+ fun `the numeric core of a prerelease is still the version`() {
+ assertEquals(AppVersion(1, 2, 0), AppVersion.parseCore("1.2.0-beta.1"))
+ }
+
+ @Test
+ fun `a malformed version is not a version`() {
+ assertNull(AppVersion.parse(null))
+ assertNull(AppVersion.parse(""))
+ assertNull(AppVersion.parse(" "))
+ assertNull(AppVersion.parse("not-a-version"))
+ assertNull(AppVersion.parse("1.x.3"))
+ assertNull(AppVersion.parse("1..3"))
+ assertNull(AppVersion.parse("1.2.3.4.5"))
+ assertNull(AppVersion.parse("v"))
+ }
+
+ @Test
+ fun `a version prints back in its canonical form`() {
+ assertEquals("1.2.3", AppVersion.parse("v1.2.3").toString())
+ assertEquals("1.2.3-beta.1", AppVersion.parse("1.2.3-beta.1").toString())
+ }
+}
diff --git a/app/src/test/java/com/discounthunter/android/update/GitHubReleaseServiceTest.kt b/app/src/test/java/com/discounthunter/android/update/GitHubReleaseServiceTest.kt
new file mode 100644
index 0000000..f05146a
--- /dev/null
+++ b/app/src/test/java/com/discounthunter/android/update/GitHubReleaseServiceTest.kt
@@ -0,0 +1,131 @@
+package com.discounthunter.android.update
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Reading the GitHub latest-release response.
+ *
+ * The parser is the boundary between a third party's response and the rest of the application, so
+ * it is written to be *lenient about shape* and *strict about meaning*: a body it does not
+ * recognise produces nothing, rather than a release with empty fields that the updater would then
+ * compare against.
+ */
+class GitHubReleaseServiceTest {
+
+ private val service = GitHubReleaseService(
+ network = com.discounthunter.android.data.net.HttpClient(
+ okhttp3.OkHttpClient(),
+ ),
+ cache = com.discounthunter.android.data.cache.PayloadCache(
+ java.io.File(System.getProperty("java.io.tmpdir"), "unused"),
+ ),
+ )
+
+ private val body = """
+ {
+ "name": "Discount Hunter 1.1.0",
+ "tag_name": "v1.1.0",
+ "body": "## Added\n\n- Deal alerts\n",
+ "published_at": "2026-10-20T12:00:00Z",
+ "html_url": "https://github.com/JuggyBob/DiscountHunterAndroid/releases/tag/v1.1.0",
+ "draft": false,
+ "prerelease": false,
+ "assets": [
+ {
+ "name": "discount-hunter-1.1.0.apk",
+ "browser_download_url": "https://github.com/JuggyBob/DiscountHunterAndroid/releases/download/v1.1.0/discount-hunter-1.1.0.apk",
+ "size": 3200000,
+ "content_type": "application/vnd.android.package-archive",
+ "digest": "sha256:0123456789abcdef"
+ }
+ ]
+ }
+ """.trimIndent()
+
+ @Test
+ fun `a release is parsed`() {
+ val release = service.parse(body)
+ assertNotNull(release)
+ assertEquals("Discount Hunter 1.1.0", release?.name)
+ assertEquals("v1.1.0", release?.tagName)
+ assertEquals("1.1.0", release?.versionLabel)
+ assertEquals("2026-10-20T12:00:00Z", release?.publishedAt)
+ assertEquals(
+ "https://github.com/JuggyBob/DiscountHunterAndroid/releases/tag/v1.1.0",
+ release?.htmlUrl,
+ )
+ assertFalse(release?.prerelease ?: true)
+ assertFalse(release?.draft ?: true)
+ }
+
+ @Test
+ fun `the assets are parsed`() {
+ val release = service.parse(body)
+ assertEquals(1, release?.assets?.size)
+ val asset = release?.assets?.first()
+ assertEquals("discount-hunter-1.1.0.apk", asset?.name)
+ assertEquals(3_200_000L, asset?.sizeBytes)
+ assertEquals("sha256:0123456789abcdef", asset?.digest)
+ assertEquals("0123456789abcdef", asset?.sha256)
+ }
+
+ @Test
+ fun `the release notes are kept`() {
+ val release = service.parse(body)
+ assertTrue(release?.body?.contains("Deal alerts") ?: false)
+ }
+
+ @Test
+ fun `an empty release body is not an error`() {
+ val empty = body.replace("\"body\": \"## Added\\n\\n- Deal alerts\\n\"", "\"body\": \"\"")
+ val release = service.parse(empty)
+ assertNotNull(release)
+ assertEquals("", release?.body)
+ }
+
+ @Test
+ fun `a release with no assets is not an error`() {
+ val none = body.replace("\"assets\": [", "\"assets\": [], \"ignored\": [")
+ val release = service.parse(none)
+ assertNotNull(release)
+ assertTrue(release?.assets?.isEmpty() ?: false)
+ assertNull(release?.installableAsset())
+ }
+
+ @Test
+ fun `a malformed body is rejected`() {
+ assertNull(service.parse("not json at all"))
+ assertNull(service.parse("{}"))
+ assertNull(service.parse("[]"))
+ assertNull(service.parse("{\"name\":\"no tag\"}"))
+ }
+
+ @Test
+ fun `an asset without a download url is skipped`() {
+ val broken = body.replace(
+ "\"browser_download_url\": \"https://github.com/JuggyBob/DiscountHunterAndroid/releases/download/v1.1.0/discount-hunter-1.1.0.apk\",",
+ "\"browser_download_url\": \"\",",
+ )
+ val release = service.parse(broken)
+ assertTrue(release?.assets?.isEmpty() ?: false)
+ }
+
+ @Test
+ fun `a prerelease is marked as one`() {
+ val preview = body.replace("\"prerelease\": false", "\"prerelease\": true")
+ assertTrue(service.parse(preview)?.prerelease ?: false)
+ }
+
+ @Test
+ fun `the endpoint points at this project repository`() {
+ assertEquals(
+ "https://api.github.com/repos/JuggyBob/DiscountHunterAndroid/releases/latest",
+ GitHubReleaseService.API_URL,
+ )
+ }
+}
diff --git a/app/src/test/java/com/discounthunter/android/update/ReleaseAssetSelectorTest.kt b/app/src/test/java/com/discounthunter/android/update/ReleaseAssetSelectorTest.kt
new file mode 100644
index 0000000..a640a74
--- /dev/null
+++ b/app/src/test/java/com/discounthunter/android/update/ReleaseAssetSelectorTest.kt
@@ -0,0 +1,109 @@
+package com.discounthunter.android.update
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+/**
+ * Which published file is the installable update.
+ *
+ * ## The rule this pins down
+ *
+ * A release can carry several APKs. Picking the first one that ends in `.apk` can hand the user
+ * the wrong file β a debug build, a source archive, a per-architecture build β and installing that
+ * is not an update. So the selection is by this project's naming convention, and when the choice is
+ * not unambiguous the answer is *nothing*, which the caller reports rather than guessing.
+ */
+class ReleaseAssetSelectorTest {
+
+ private fun asset(name: String, size: Long = 3_000_000) = ReleaseAsset(
+ name = name,
+ downloadUrl = "https://github.com/JuggyBob/DiscountHunterAndroid/releases/download/v1.1.0/$name",
+ sizeBytes = size,
+ contentType = "application/vnd.android.package-archive",
+ )
+
+ private fun release(vararg assets: ReleaseAsset) = ReleaseInfo(
+ name = "Discount Hunter 1.1.0",
+ tagName = "v1.1.0",
+ version = AppVersion.parse("v1.1.0"),
+ body = "notes",
+ publishedAt = "2026-10-20T12:00:00Z",
+ htmlUrl = "https://github.com/JuggyBob/DiscountHunterAndroid/releases/tag/v1.1.0",
+ assets = assets.toList(),
+ )
+
+ @Test
+ fun `the release apk is selected`() {
+ val chosen = release(asset("discount-hunter-1.1.0.apk")).installableAsset()
+ assertEquals("discount-hunter-1.1.0.apk", chosen?.name)
+ }
+
+ @Test
+ fun `a source archive is not selected`() {
+ assertNull(release(asset("Source code (zip)")).installableAsset())
+ }
+
+ @Test
+ fun `a debug apk is not selected`() {
+ assertNull(
+ release(asset("discount-hunter-1.1.0-debug.apk")).installableAsset(),
+ )
+ }
+
+ @Test
+ fun `an apk that is not this project is not selected`() {
+ assertNull(release(asset("some-other-app-2.0.apk")).installableAsset())
+ }
+
+ @Test
+ fun `no apk at all means no update`() {
+ assertNull(release().installableAsset())
+ }
+
+ @Test
+ fun `two candidate apks mean no unambiguous choice`() {
+ // Two release builds and no principled way to choose between them: the caller has to be
+ // told, rather than being handed one at random.
+ val chosen = release(
+ asset("discount-hunter-1.1.0.apk"),
+ asset("discount-hunter-1.1.0-alt.apk"),
+ ).installableAsset()
+ assertNull(chosen)
+ }
+
+ @Test
+ fun `a debug and a release apk still leave one candidate`() {
+ val chosen = release(
+ asset("discount-hunter-1.1.0.apk"),
+ asset("discount-hunter-1.1.0-debug.apk"),
+ ).installableAsset()
+ assertEquals("discount-hunter-1.1.0.apk", chosen?.name)
+ }
+
+ @Test
+ fun `an app bundle is not selected`() {
+ assertNull(release(asset("discount-hunter-1.1.0.aab")).installableAsset())
+ }
+
+ @Test
+ fun `a digest is read from the sha256 prefix`() {
+ val withDigest = ReleaseAsset(
+ name = "discount-hunter-1.1.0.apk",
+ downloadUrl = "https://example.invalid/a.apk",
+ sizeBytes = 1,
+ digest = "sha256:abc123",
+ )
+ assertEquals("abc123", withDigest.sha256)
+ }
+
+ @Test
+ fun `a missing digest is reported as missing`() {
+ val without = ReleaseAsset(
+ name = "a.apk",
+ downloadUrl = "https://example.invalid/a.apk",
+ sizeBytes = 1,
+ )
+ assertNull(without.sha256)
+ }
+}
diff --git a/app/src/test/java/com/discounthunter/android/update/ReleaseNotesFormatterTest.kt b/app/src/test/java/com/discounthunter/android/update/ReleaseNotesFormatterTest.kt
new file mode 100644
index 0000000..03ecb9d
--- /dev/null
+++ b/app/src/test/java/com/discounthunter/android/update/ReleaseNotesFormatterTest.kt
@@ -0,0 +1,118 @@
+package com.discounthunter.android.update
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Rendering release notes safely.
+ *
+ * Release notes are somebody else's text. The formatter turns a small, known subset of Markdown
+ * into styled lines and nothing else: no HTML is passed through, no image is fetched, and no link
+ * is made tappable.
+ */
+class ReleaseNotesFormatterTest {
+
+ @Test
+ fun `a heading becomes a heading line`() {
+ val lines = ReleaseNotesFormatter.parse("## Added")
+ assertEquals(1, lines.size)
+ assertEquals("Added", lines[0].text)
+ assertEquals(ReleaseNotesFormatter.Style.HEADING, lines[0].style)
+ }
+
+ @Test
+ fun `a subheading is distinguished from a heading`() {
+ val lines = ReleaseNotesFormatter.parse("### Fixed")
+ assertEquals(ReleaseNotesFormatter.Style.SUBHEADING, lines[0].style)
+ }
+
+ @Test
+ fun `a bullet becomes a bullet line`() {
+ val lines = ReleaseNotesFormatter.parse("- Deal alerts")
+ assertEquals(ReleaseNotesFormatter.Style.BULLET, lines[0].style)
+ assertEquals("Deal alerts", lines[0].text)
+ }
+
+ @Test
+ fun `an asterisk bullet is also a bullet`() {
+ val lines = ReleaseNotesFormatter.parse("* Another change")
+ assertEquals(ReleaseNotesFormatter.Style.BULLET, lines[0].style)
+ }
+
+ @Test
+ fun `plain text stays plain text`() {
+ val lines = ReleaseNotesFormatter.parse("Just a sentence.")
+ assertEquals(ReleaseNotesFormatter.Style.TEXT, lines[0].style)
+ assertEquals("Just a sentence.", lines[0].text)
+ }
+
+ @Test
+ fun `a horizontal rule is recognised`() {
+ val lines = ReleaseNotesFormatter.parse("---")
+ assertEquals(ReleaseNotesFormatter.Style.RULE, lines[0].style)
+ }
+
+ @Test
+ fun `blank lines are dropped`() {
+ val lines = ReleaseNotesFormatter.parse("\n\nOne\n\n\nTwo\n")
+ assertEquals(2, lines.size)
+ }
+
+ @Test
+ fun `html tags are stripped rather than shown`() {
+ val lines = ReleaseNotesFormatter.parse("Bold and ")
+ assertEquals("Bold and alert(1)", lines[0].text)
+ assertTrue(lines[0].text.none { it == '<' })
+ }
+
+ @Test
+ fun `an empty body produces nothing`() {
+ assertTrue(ReleaseNotesFormatter.parse("").isEmpty())
+ assertTrue(ReleaseNotesFormatter.parse(" \n \n").isEmpty())
+ }
+
+ @Test
+ fun `a long body keeps every line`() {
+ val body = (1..200).joinToString("\n") { "Line $it" }
+ assertEquals(200, ReleaseNotesFormatter.parse(body).size)
+ }
+
+ @Test
+ fun `a link keeps its text and shows the address`() {
+ val segments = ReleaseNotesFormatter.inline("See [the changelog](https://example.invalid/x)")
+ assertEquals(
+ "See the changelog (https://example.invalid/x)",
+ segments.joinToString("") { it.text },
+ )
+ }
+
+ @Test
+ fun `a link is never a separate tappable segment`() {
+ // The address is shown as plain text. A link in somebody else's release notes is not
+ // something to make clickable.
+ val segments = ReleaseNotesFormatter.inline("[click me](https://example.invalid/evil)")
+ assertEquals(2, segments.size)
+ assertEquals("click me", segments[0].text)
+ assertTrue(segments.none { it.text == "https://example.invalid/evil" })
+ }
+
+ @Test
+ fun `bold text is marked as bold`() {
+ val segments = ReleaseNotesFormatter.inline("a **bold** word")
+ assertTrue(segments.any { it.bold && it.text == "bold" })
+ }
+
+ @Test
+ fun `inline code is marked as code`() {
+ val segments = ReleaseNotesFormatter.inline("run `./gradlew test`")
+ assertTrue(segments.any { it.code && it.text == "./gradlew test" })
+ }
+
+ @Test
+ fun `plain text is one segment`() {
+ val segments = ReleaseNotesFormatter.inline("nothing special")
+ assertEquals(1, segments.size)
+ assertEquals("nothing special", segments[0].text)
+ }
+}
diff --git a/docs/screenshots/10-about-whats-new.png b/docs/screenshots/10-about-whats-new.png
new file mode 100644
index 0000000..a99daf2
Binary files /dev/null and b/docs/screenshots/10-about-whats-new.png differ