Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Signed Android releases that update themselves
Beea158d6e13e90
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex f00612f..1b892a5 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -1,6 +1,7 @@# SPDX-License-Identifier: GPL-3.0-or-later-# A tag like v0.1.0 builds the Windows installer and puts it on a draft-# GitHub release, which a maintainer reviews and publishes.+# A tag like v0.1.0 builds the Windows installer and the signed Android app,+# and puts both on a draft GitHub release (with their SHA-256 sums, which+# the apps' updaters check), for a maintainer to review and publish.name: Releaseon:@@ -15,16 +16,24 @@ env:QT_VERSION: "6.12.0"jobs:+ version:+ name: The tag matches the version+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ - run: |+ version=$(grep -m1 '^version = ' Cargo.toml | cut -d'"' -f2)+ if [ "v$version" != "${{ github.ref_name }}" ]; then+ echo "::error::tag ${{ github.ref_name }} but Cargo.toml says $version"+ exit 1+ fi+windows:name: Windows installer (x64)+ needs: versionruns-on: windows-lateststeps:- uses: actions/checkout@v7- - name: The tag matches the version- shell: pwsh- run: |- $version = (Select-String -Path Cargo.toml -Pattern '^version = "([^"]+)"' | Select-Object -First 1).Matches[0].Groups[1].Value- if ("v$version" -ne "${{ github.ref_name }}") { throw "tag ${{ github.ref_name }} but Cargo.toml says $version" }- name: Install the pinned Rust toolchainrun: rustup show active-toolchain || rustup toolchain install- name: Install Qt@@ -49,12 +58,74 @@ jobs:- name: Check it installs and uninstallsshell: pwshrun: ./scripts/smoke-installer.ps1- - name: Draft the release- shell: pwsh+ - uses: actions/upload-artifact@v7+ with:+ name: windows+ path: target/package/*-setup.exe++ android:+ name: Android app (signed)+ needs: version+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ - name: Install the pinned Rust toolchain and the Android targets+ run: |+ rustup show active-toolchain || rustup toolchain install+ rustup target add aarch64-linux-android armv7-linux-androideabi+ - name: Install cargo-ndk+ run: cargo install --locked cargo-ndk+ - uses: actions/setup-java@v6+ with:+ distribution: temurin+ java-version: "21"+ - uses: android-actions/setup-android@v4+ with:+ cmdline-tools-version: "16111833"+ packages: "platforms;android-37.0 ndk;30.0.16248370 build-tools;37.0.0"+ - uses: gradle/actions/setup-gradle@v6+ - name: The signing key+ env:+ KEYSTORE: ${{ secrets.ANDROID_KEYSTORE }}+ run: |+ if [ -z "$KEYSTORE" ]; then echo "::error::the ANDROID_KEYSTORE secret isn't set"; exit 1; fi+ echo "$KEYSTORE" | base64 -d > "$RUNNER_TEMP/release.jks"+ - name: Build+ working-directory: android+ env:+ NECTARLINK_KEYSTORE: ${{ runner.temp }}/release.jks+ NECTARLINK_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}+ # Phones: 64-bit ARM, and 32-bit ARM for older ones.+ run: ./gradlew --no-daemon assembleRelease -Pnectarlink.abis=arm64-v8a,armeabi-v7a+ - name: Check the signature, and name the app+ run: |+ apk=android/app/build/outputs/apk/release/app-release.apk+ "$ANDROID_HOME/build-tools/37.0.0/apksigner" verify --print-certs "$apk"+ mkdir -p out+ cp "$apk" "out/Nectarlink-${GITHUB_REF_NAME#v}-android.apk"+ - name: Forget the key+ if: always()+ run: rm -f "$RUNNER_TEMP/release.jks"+ - uses: actions/upload-artifact@v7+ with:+ name: android+ path: out/*.apk++ publish:+ name: Draft the release+ needs: [windows, android]+ runs-on: ubuntu-latest+ steps:+ - uses: actions/download-artifact@v7+ with:+ path: files+ merge-multiple: true+ - name: Draft itenv:GH_TOKEN: ${{ github.token }}run: |- $setup = (Get-ChildItem target/package/*-setup.exe).FullName- $hash = (Get-FileHash $setup -Algorithm SHA256).Hash.ToLower()- "$hash $(Split-Path -Leaf $setup)" | Set-Content target/package/SHA256SUMS.txt- gh release create "${{ github.ref_name }}" $setup target/package/SHA256SUMS.txt --draft --generate-notes --title "Nectarlink ${{ github.ref_name }}"+ cd files+ sha256sum *.exe *.apk > SHA256SUMS.txt+ cat SHA256SUMS.txt+ gh release create "${{ github.ref_name }}" *.exe *.apk SHA256SUMS.txt \+ --repo "${{ github.repository }}" --draft --generate-notes --title "Nectarlink ${{ github.ref_name }}"diff --git a/Cargo.toml b/Cargo.tomlindex 0cf548b..f99fe99 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -62,6 +62,12 @@ missing_debug_implementations = "warn"[workspace.lints.clippy]all = { level = "warn", priority = -1 }+# Debug builds: full debug info for our crates, line tables only for+# dependencies (backtraces still name their lines). Keeps target/debug from+# growing by gigabytes per rebuild.+[profile.dev.package."*"]+debug = "line-tables-only"+[profile.release]lto = "thin"codegen-units = 1diff --git a/README.md b/README.mdindex 267bbc0..4d7b8a0 100644--- a/README.md+++ b/README.md@@ -106,13 +106,13 @@ place and tested; the user-facing features of Phase 1 come next.connecting (firewall, a public network, a VPN) and fixes what it can.- **Windows installer**: installs for everyone on the PC, allows the appthrough Windows Firewall, starts it with Windows, and uninstalls cleanly.- Each `v*` tag drafts a GitHub release with the installer. Installed copies- update themselves from GitHub releases (checked with SHA-256).+ Each `v*` tag drafts a GitHub release with the installer and the signed+ Android app; both apps update themselves from published releases, checked+ against their SHA-256 sums.- **Command-line client** for development and testing (`nectarlink`).-**Next**: the Android app updating itself (it needs signed release builds-first). Then Phase 2: mirroring, messages, calls and the other features in-the plan.+**Next**: Phase 2: mirroring, messages, calls and the other features in the+plan.## Screenshotsdiff --git a/android/app/build.gradle.kts b/android/app/build.gradle.ktsindex 45a3c2b..d115a96 100644--- a/android/app/build.gradle.kts+++ b/android/app/build.gradle.kts@@ -6,6 +6,14 @@ plugins {alias(libs.plugins.kotlin.compose)}+// The version comes from the workspace (Cargo.toml), like the PC app's.+val appVersion: String = rootProject.file("../Cargo.toml").readLines()+ .first { it.startsWith("version = ") }+ .substringAfter('"').substringBefore('"')+/** 1.2.3 → 1002003: every release must have a larger code than the last. */+val appVersionCode: Int = appVersion.substringBefore('-').split('.').map(String::toInt)+ .let { (major, minor, patch) -> major * 1_000_000 + minor * 1_000 + patch }+android {namespace = "app.nectarlink.android"compileSdk = 37@@ -15,12 +23,28 @@ android {applicationId = "app.nectarlink"minSdk = 26targetSdk = 37- versionCode = 1- versionName = "0.0.1"+ versionCode = appVersionCode+ versionName = appVersion+ }++ // Release builds are signed with the project's key when CI provides it+ // (NECTARLINK_KEYSTORE: a .jks file; NECTARLINK_KEYSTORE_PASSWORD).+ // Without it, a release build comes out unsigned.+ val keystore = System.getenv("NECTARLINK_KEYSTORE")?.let(::file)?.takeIf { it.exists() }+ signingConfigs {+ if (keystore != null) {+ create("release") {+ storeFile = keystore+ storePassword = System.getenv("NECTARLINK_KEYSTORE_PASSWORD")+ keyAlias = "nectarlink"+ keyPassword = System.getenv("NECTARLINK_KEYSTORE_PASSWORD")+ }+ }}buildTypes {release {+ if (keystore != null) signingConfig = signingConfigs.getByName("release")isMinifyEnabled = trueisShrinkResources = trueproguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 3c40e3e..2299c24 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -19,6 +19,8 @@<!-- Asking to run unrestricted in the background: phones such as Samsung'sotherwise freeze the app, and PCs can't reach it. --><uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />+ <!-- Installing its own updates from GitHub releases (the user allows it once). -->+ <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /><!-- Names and icons of the apps whose notifications are mirrored: Androidhides other apps unless they're declared here. -->@@ -86,6 +88,11 @@android:name=".files.TransferNotifications$CancelReceiver"android:exported="false" />+ <!-- Android's answers while installing an update. -->+ <receiver+ android:name=".update.AppUpdater$InstallResult"+ android:exported="false" />+<!-- The PC media notification's buttons (Android 12 and earlier). --><receiverandroid:name=".media.PcMedia$CommandReceiver"diff --git a/android/app/src/main/kotlin/app/nectarlink/android/NectarlinkApplication.kt b/android/app/src/main/kotlin/app/nectarlink/android/NectarlinkApplication.ktindex 45a3896..b6d6082 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/NectarlinkApplication.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/NectarlinkApplication.kt@@ -3,6 +3,7 @@ package app.nectarlink.androidimport android.app.Applicationimport app.nectarlink.android.core.Core+import app.nectarlink.android.update.AppUpdaterimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJob@@ -13,6 +14,9 @@ class NectarlinkApplication : Application() {val core: Core by lazy { Core(this, scope) }+ /** Updates from GitHub releases (release builds only). */+ val updater: AppUpdater by lazy { AppUpdater(this) }+override fun onCreate() {super.onCreate()core.start()diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.ktindex dbb2df1..db703ef 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt@@ -32,9 +32,12 @@ import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.res.stringResourceimport androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.lifecycle.lifecycleScope+import kotlinx.coroutines.launchimport app.nectarlink.android.NectarlinkApplicationimport app.nectarlink.android.Rimport app.nectarlink.android.core.Core@@ -83,7 +86,9 @@ class MainActivity : ComponentActivity() {override fun onResume() {super.onResume()// Back from Settings, maybe with notification access changed.- (application as NectarlinkApplication).core.refreshNotificationAccess()+ val app = application as NectarlinkApplication+ app.core.refreshNotificationAccess()+ if (app.updater.enabled) lifecycleScope.launch { app.updater.checkIfDue() }}override fun onNewIntent(intent: Intent) {@@ -164,6 +169,7 @@ private fun App(core: Core, state: CoreState, preferences: Preferences) {onPairNew = { pairing = true },onRefresh = core::refresh,onPower = core::pcPower,+ updater = (LocalContext.current.applicationContext as NectarlinkApplication).updater,onSendFiles = core::sendFiles,onCancelTransfer = core::cancelTransfer,modifier = modifier,@@ -174,6 +180,7 @@ private fun App(core: Core, state: CoreState, preferences: Preferences) {onAppearance = preferences::update,onUnpair = core::unpair,onPairNew = { pairing = true },+ updater = (LocalContext.current.applicationContext as NectarlinkApplication).updater,modifier = modifier,)}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.ktindex cf30381..513f028 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt@@ -45,6 +45,8 @@ import androidx.compose.ui.res.pluralStringResourceimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.unit.dpimport app.nectarlink.android.R+import app.nectarlink.android.update.AppUpdater+import app.nectarlink.android.update.UpdateCardimport app.nectarlink.android.clipboard.SendActivityimport app.nectarlink.android.core.BackgroundAccessimport app.nectarlink.android.core.CoreState@@ -72,6 +74,7 @@ fun HomeScreen(onPairNew: () -> Unit,onRefresh: () -> Unit,onPower: (pcId: String, sleep: Boolean) -> Unit,+ updater: AppUpdater,onSendFiles: (pcId: String, uris: List<Uri>) -> Unit,onCancelTransfer: (id: String) -> Unit,modifier: Modifier = Modifier,@@ -112,6 +115,7 @@ fun HomeScreen(state.ringingFrom?.let { from ->item { RingingBanner(from, onStopRinging) }}+ item { UpdateCard(updater) }if (state.devices.isNotEmpty() && !state.backgroundUnrestricted) {item {val context = LocalContext.currentdiff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.ktindex 8136435..fd5630f 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt@@ -43,6 +43,8 @@ import androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.unit.dpimport app.nectarlink.android.BuildConfigimport app.nectarlink.android.R+import app.nectarlink.android.update.AppUpdater+import app.nectarlink.android.update.CheckForUpdatesimport app.nectarlink.android.core.CoreStateimport app.nectarlink.android.core.CoreStatusimport app.nectarlink.android.core.Device@@ -58,6 +60,7 @@ fun SettingsScreen(onAppearance: ((Appearance) -> Appearance) -> Unit,onUnpair: (String) -> Unit,onPairNew: () -> Unit,+ updater: AppUpdater,modifier: Modifier = Modifier,) {var confirmUnpair by remember { mutableStateOf<Device?>(null) }@@ -146,6 +149,7 @@ fun SettingsScreen(Section(stringResource(R.string.settings_about)) {Text(stringResource(R.string.about_version, BuildConfig.VERSION_NAME), style = MaterialTheme.typography.bodyMedium)+ CheckForUpdates(updater)(state.status as? CoreStatus.Ready)?.let {Text(it.deviceId,diff --git a/android/app/src/main/kotlin/app/nectarlink/android/update/AppUpdater.kt b/android/app/src/main/kotlin/app/nectarlink/android/update/AppUpdater.ktnew file mode 100644index 0000000..d797d84--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/update/AppUpdater.kt@@ -0,0 +1,265 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.update++import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.pm.PackageInstaller+import android.os.Build+import android.provider.Settings+import android.util.Log+import androidx.core.content.edit+import androidx.core.net.toUri+import app.nectarlink.android.BuildConfig+import app.nectarlink.android.NectarlinkApplication+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.withContext+import org.json.JSONObject+import java.io.File+import java.net.HttpURLConnection+import java.net.URL+import java.security.MessageDigest++/**+ * Updates from GitHub releases: checks the latest release, and installs a+ * newer signed APK after checking it against the release's SHA-256 sums.+ * Android only installs it over this app when it's signed with the same+ * key, so only release builds update themselves (debug builds are signed+ * differently).+ */+class AppUpdater(context: Context) {+ private val context = context.applicationContext+ private val prefs = context.getSharedPreferences("updates", Context.MODE_PRIVATE)++ /** A newer release. */+ data class Update(val version: String, val notesUrl: String, internal val apkUrl: String, internal val apkName: String, internal val sumsUrl: String)++ sealed interface State {+ data object Idle : State+ data object Checking : State+ data class Available(val update: Update) : State+ data class Downloading(val update: Update) : State+ /** Waiting for Android (and the user) to install it. */+ data class Installing(val update: Update) : State+ data class Failed(val update: Update?, val reason: Reason) : State+ }++ enum class Reason { Offline, Damaged, NotAllowed, Install }++ private val _state = MutableStateFlow<State>(State.Idle)+ val state: StateFlow<State> = _state.asStateFlow()++ /** Whether this build updates itself. */+ val enabled: Boolean get() = !BuildConfig.DEBUG++ /** Checks at most once a day (call when the app comes to the front). */+ suspend fun checkIfDue() {+ val last = prefs.getLong(LAST_CHECK, 0)+ if (System.currentTimeMillis() - last < CHECK_EVERY_MS) return+ check()+ }++ /** Checks now; returns whether an update is available. */+ suspend fun check(): Boolean {+ if (!enabled) return false+ _state.value = State.Checking+ val found = withContext(Dispatchers.IO) {+ runCatching { latest() }.onFailure { Log.i(TAG, "couldn't check for updates", it) }+ }+ prefs.edit { putLong(LAST_CHECK, System.currentTimeMillis()) }+ _state.value = found.fold(+ onSuccess = { update -> update?.let { State.Available(it) } ?: State.Idle },+ onFailure = { State.Failed(null, Reason.Offline) },+ )+ return _state.value is State.Available+ }++ private fun latest(): Update? {+ val release = JSONObject(String(get(LATEST, 1 shl 20)))+ if (release.optBoolean("draft") || release.optBoolean("prerelease")) return null+ val version = release.getString("tag_name").removePrefix("v")+ if (!isNewer(version, BuildConfig.VERSION_NAME)) return null+ val assets = release.getJSONArray("assets")+ var apk: JSONObject? = null+ var sums: JSONObject? = null+ for (i in 0 until assets.length()) {+ val asset = assets.getJSONObject(i)+ val name = asset.getString("name")+ if (name.endsWith("-android.apk")) apk = asset+ if (name == "SHA256SUMS.txt") sums = asset+ }+ if (apk == null || sums == null) return null+ return Update(+ version = version,+ notesUrl = release.getString("html_url"),+ apkUrl = apk.getString("browser_download_url"),+ apkName = apk.getString("name"),+ sumsUrl = sums.getString("browser_download_url"),+ )+ }++ /** Whether this app may install apps (the user allows it once, in Settings). */+ fun canInstall(): Boolean = context.packageManager.canRequestPackageInstalls()++ /** Android's screen where the user lets Nectarlink install updates. */+ fun allowInstallsIntent(): Intent =+ Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, "package:${context.packageName}".toUri())+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)++ /** Downloads, checks and hands the update to Android's installer. */+ suspend fun install(update: Update) {+ if (!canInstall()) {+ _state.value = State.Failed(update, Reason.NotAllowed)+ return+ }+ _state.value = State.Downloading(update)+ val apk = withContext(Dispatchers.IO) { runCatching { download(update) } }.getOrElse {+ Log.w(TAG, "update download failed", it)+ _state.value = State.Failed(update, if (it is DamagedException) Reason.Damaged else Reason.Offline)+ return+ }+ _state.value = State.Installing(update)+ withContext(Dispatchers.IO) { runCatching { commit(apk) } }.onFailure {+ Log.w(TAG, "couldn't start the install", it)+ _state.value = State.Failed(update, Reason.Install)+ }+ }++ private class DamagedException : Exception("checksum mismatch")++ private fun download(update: Update): File {+ val sums = String(get(update.sumsUrl, 64 * 1024))+ val expected = listedHash(sums, update.apkName) ?: throw DamagedException()+ val dir = File(context.cacheDir, "updates").apply { deleteRecursively(); mkdirs() }+ val file = File(dir, update.apkName)+ val digest = MessageDigest.getInstance("SHA-256")+ open(update.apkUrl).inputStream.use { input ->+ file.outputStream().use { output ->+ val buffer = ByteArray(256 * 1024)+ var total = 0L+ while (true) {+ val read = input.read(buffer)+ if (read < 0) break+ total += read+ if (total > MAX_APK) throw DamagedException()+ digest.update(buffer, 0, read)+ output.write(buffer, 0, read)+ }+ }+ }+ val actual = digest.digest().joinToString("") { "%02x".format(it) }+ if (actual != expected) {+ file.delete()+ throw DamagedException()+ }+ return file+ }++ private fun commit(apk: File) {+ val installer = context.packageManager.packageInstaller+ val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {+ setAppPackageName(context.packageName)+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED)+ }+ }+ val id = installer.createSession(params)+ installer.openSession(id).use { session ->+ apk.inputStream().use { input ->+ session.openWrite("base.apk", 0, apk.length()).use { output ->+ input.copyTo(output)+ session.fsync(output)+ }+ }+ val done = PendingIntent.getBroadcast(+ context,+ id,+ Intent(context, InstallResult::class.java),+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE,+ )+ session.commit(done.intentSender)+ }+ }++ /** Android's answer: ask the user to confirm, or it's done (or failed). */+ class InstallResult : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ when (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {+ PackageInstaller.STATUS_PENDING_USER_ACTION -> {+ val confirm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)+ } else {+ @Suppress("DEPRECATION")+ intent.getParcelableExtra(Intent.EXTRA_INTENT)+ }+ confirm?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)?.let(context::startActivity)+ }+ PackageInstaller.STATUS_SUCCESS -> Unit // The new version starts fresh.+ else -> {+ Log.w(TAG, "install failed: ${intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)}")+ (context.applicationContext as NectarlinkApplication).updater.installFailed()+ }+ }+ }+ }++ /** Android didn't install it. */+ internal fun installFailed() {+ _state.update { s -> State.Failed((s as? State.Installing)?.update, Reason.Install) }+ }++ companion object {+ private const val TAG = "AppUpdater"+ private const val LATEST = "https://api.github.com/repos/thtbee/nectarlink/releases/latest"+ private const val LAST_CHECK = "lastCheck"+ private const val CHECK_EVERY_MS = 24L * 3600 * 1000+ private const val MAX_APK = 300L * 1024 * 1024++ private fun open(url: String): HttpURLConnection =+ (URL(url).openConnection() as HttpURLConnection).apply {+ connectTimeout = 10_000+ readTimeout = 60_000+ instanceFollowRedirects = true+ setRequestProperty("User-Agent", "Nectarlink/${BuildConfig.VERSION_NAME} (Android)")+ setRequestProperty("Accept", "application/vnd.github+json, application/octet-stream")+ if (responseCode != 200) throw java.io.IOException("HTTP $responseCode")+ }++ private fun get(url: String, limit: Int): ByteArray =+ open(url).inputStream.use { input ->+ val bytes = input.readBytes()+ if (bytes.size > limit) throw java.io.IOException("too large")+ bytes+ }++ /** The SHA-256 a sums file lists for `name` (`<hex> <name>` lines). */+ fun listedHash(sums: String, name: String): String? = sums.lineSequence().firstNotNullOfOrNull { line ->+ val parts = line.trim().split(Regex("\\s+"), limit = 2)+ val hash = parts.getOrNull(0)?.lowercase()+ val file = parts.getOrNull(1)?.trimStart('*')+ hash?.takeIf { file == name && it.length == 64 }+ }++ /** `1.2.3` style versions; a release is newer than its pre-releases. */+ fun isNewer(candidate: String, current: String): Boolean {+ fun parse(v: String): Pair<List<Int>, String?>? {+ val numbers = v.substringBefore('-').split('.').map { it.toIntOrNull() ?: return null }+ if (numbers.size !in 2..3) return null+ return (numbers + List(3 - numbers.size) { 0 }) to v.substringAfter('-', "").ifEmpty { null }+ }+ val (a, aPre) = parse(candidate) ?: return false+ val (b, bPre) = parse(current) ?: return false+ for (i in 0..2) if (a[i] != b[i]) return a[i] > b[i]+ return when {+ aPre == null && bPre != null -> true+ aPre != null && bPre != null -> aPre > bPre+ else -> false+ }+ }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/update/UpdateCard.kt b/android/app/src/main/kotlin/app/nectarlink/android/update/UpdateCard.ktnew file mode 100644index 0000000..7e96159--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/update/UpdateCard.kt@@ -0,0 +1,120 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.update++import android.content.Intent+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Button+import androidx.compose.material3.LinearProgressIndicator+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedButton+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.core.net.toUri+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import app.nectarlink.android.R+import kotlinx.coroutines.launch++/** "Nectarlink 0.2.0 is available", while there's an update to talk about. */+@Composable+fun UpdateCard(updater: AppUpdater, modifier: Modifier = Modifier) {+ val state by updater.state.collectAsStateWithLifecycle()+ val update = when (val s = state) {+ is AppUpdater.State.Available -> s.update+ is AppUpdater.State.Downloading -> s.update+ is AppUpdater.State.Installing -> s.update+ is AppUpdater.State.Failed -> s.update+ else -> null+ } ?: return+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ val failure = (state as? AppUpdater.State.Failed)?.reason+ Surface(+ shape = MaterialTheme.shapes.extraLarge,+ color = MaterialTheme.colorScheme.secondaryContainer,+ contentColor = MaterialTheme.colorScheme.onSecondaryContainer,+ modifier = modifier,+ ) {+ Column(Modifier.fillMaxWidth().padding(20.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {+ Text(stringResource(R.string.update_title, update.version), style = MaterialTheme.typography.titleMedium)+ Text(+ stringResource(+ when {+ state is AppUpdater.State.Downloading -> R.string.update_downloading+ state is AppUpdater.State.Installing -> R.string.update_installing+ failure == AppUpdater.Reason.NotAllowed -> R.string.update_not_allowed+ failure == AppUpdater.Reason.Damaged -> R.string.update_damaged+ failure == AppUpdater.Reason.Install -> R.string.update_install_failed+ failure != null -> R.string.update_offline+ else -> R.string.update_text+ },+ ),+ style = MaterialTheme.typography.bodyMedium,+ )+ if (state is AppUpdater.State.Downloading || state is AppUpdater.State.Installing) {+ LinearProgressIndicator(Modifier.fillMaxWidth())+ }+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ if (failure == AppUpdater.Reason.NotAllowed && !updater.canInstall()) {+ Button(onClick = { context.startActivity(updater.allowInstallsIntent()) }) {+ Text(stringResource(R.string.action_allow))+ }+ } else {+ Button(+ enabled = state is AppUpdater.State.Available || state is AppUpdater.State.Failed,+ onClick = { scope.launch { updater.install(update) } },+ ) {+ Text(stringResource(R.string.action_update))+ }+ }+ TextButton(onClick = {+ context.startActivity(Intent(Intent.ACTION_VIEW, update.notesUrl.toUri()))+ }) {+ Text(stringResource(R.string.update_whats_new))+ }+ }+ }+ }+}++/** "Check for updates" in Settings, with what it found. */+@Composable+fun CheckForUpdates(updater: AppUpdater) {+ if (!updater.enabled) return+ val scope = rememberCoroutineScope()+ val state by updater.state.collectAsStateWithLifecycle()+ var checked by remember { mutableStateOf(false) }+ OutlinedButton(+ enabled = state !is AppUpdater.State.Checking && state !is AppUpdater.State.Downloading,+ onClick = {+ scope.launch {+ updater.check()+ checked = true+ }+ },+ ) {+ Text(stringResource(R.string.update_check))+ }+ if (checked) {+ val text = when (state) {+ AppUpdater.State.Idle -> R.string.update_up_to_date+ is AppUpdater.State.Failed -> R.string.update_check_failed+ else -> null+ }+ text?.let { Text(stringResource(it), style = MaterialTheme.typography.bodySmall) }+ }+}diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 1fc9abe..c90bad7 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -120,6 +120,19 @@<string name="action_unpair">Unpair</string><string name="action_pair_new">Pair another PC</string><string name="action_refresh">Refresh</string>+ <string name="action_update">Update</string>+ <string name="update_title">Nectarlink %1$s is available</string>+ <string name="update_text">Get the latest improvements and fixes.</string>+ <string name="update_downloading">Downloading…</string>+ <string name="update_installing">Installing. Android may ask you to confirm.</string>+ <string name="update_not_allowed">Allow Nectarlink to install its updates, then come back and tap Update.</string>+ <string name="update_damaged">The download was damaged, so it wasn’t installed. Try again.</string>+ <string name="update_offline">The update couldn’t be downloaded. Try again when you’re online.</string>+ <string name="update_install_failed">Android didn’t install the update. Try again.</string>+ <string name="update_whats_new">What’s new</string>+ <string name="update_check">Check for updates</string>+ <string name="update_up_to_date">Nectarlink is up to date.</string>+ <string name="update_check_failed">Couldn’t check for updates. Check your internet connection.</string><string name="action_lock_pc">Lock PC</string><string name="action_sleep_pc">Sleep</string><string name="pc_locked">%1$s is locked.</string>diff --git a/android/app/src/test/kotlin/app/nectarlink/android/update/AppUpdaterTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/update/AppUpdaterTest.ktnew file mode 100644index 0000000..08fdd2f--- /dev/null+++ b/android/app/src/test/kotlin/app/nectarlink/android/update/AppUpdaterTest.kt@@ -0,0 +1,30 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.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++class AppUpdaterTest {+ @Test+ fun versionsCompare() {+ assertTrue(AppUpdater.isNewer("0.1.0", "0.0.1"))+ assertTrue(AppUpdater.isNewer("1.0", "0.9.9"))+ assertTrue(AppUpdater.isNewer("0.2.0", "0.2.0-beta.1"))+ assertTrue(AppUpdater.isNewer("0.2.0-beta.2", "0.2.0-beta.1"))+ assertFalse(AppUpdater.isNewer("0.0.1", "0.0.1"))+ assertFalse(AppUpdater.isNewer("0.0.1", "0.1.0"))+ assertFalse(AppUpdater.isNewer("garbage", "0.1.0"))+ }++ @Test+ fun findsTheApkHash() {+ val hash = "a".repeat(64)+ val sums = "$hash Nectarlink-9.0.0-android.apk\n${"b".repeat(64)} Nectarlink-9.0.0-x64-setup.exe\n"+ assertEquals(hash, AppUpdater.listedHash(sums, "Nectarlink-9.0.0-android.apk"))+ assertNull(AppUpdater.listedHash(sums, "missing.apk"))+ assertEquals("c".repeat(64), AppUpdater.listedHash("${"C".repeat(64)} *x.apk", "x.apk"))+ }+}