Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: implement in-app update mechanism with remote version checking and APK installation support

Rishabh Bajpaib3755fc2cda1
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 99ea31a..219615f 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -70,6 +70,8 @@
<!-- Android 13+: shows the assistive-ball foreground-service notification (service runs
regardless of grant). -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+ <!-- In-app APK updater permission for launching PackageInstaller -->
+ <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- Tier 4: run_termux_command. Declared by Termux with protectionLevel="dangerous", so it
still needs a runtime grant; Termux additionally requires allow-external-apps=true. -->
diff --git a/app/src/main/java/com/gotcha/ui/AboutScreen.kt b/app/src/main/java/com/gotcha/ui/AboutScreen.kt
index 3eed7f0..f8ebe73 100644
--- a/app/src/main/java/com/gotcha/ui/AboutScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/AboutScreen.kt
@@ -6,21 +6,32 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
+import androidx.compose.material3.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import com.gotcha.BuildConfig
import com.gotcha.tools.CompanyInfoTool
+import com.gotcha.updater.AppUpdateManager
+import com.gotcha.updater.UpdateStatus
+import kotlinx.coroutines.launch
/**
* About Us: the hub for everything about who made this app and what using it
@@ -45,6 +56,8 @@ fun AboutScreen(
)
}
HorizontalDivider(thickness = 1.dp)
+ AppUpdateSection()
+ HorizontalDivider(thickness = 1.dp)
}
}
@@ -119,3 +132,171 @@ private val LINKS = listOf(
"GitHub" to "https://github.com/Rishabh-Bajpai",
)
+
+@Composable
+fun AppUpdateSection() {
+ val context = LocalContext.current
+ val scope = rememberCoroutineScope()
+ val updateManager = remember { AppUpdateManager.shared }
+ var status by remember { mutableStateOf<UpdateStatus>(UpdateStatus.Idle) }
+ var busy by remember { mutableStateOf(false) }
+ val lifecycleOwner = LocalLifecycleOwner.current
+
+ DisposableEffect(lifecycleOwner) {
+ val observer = LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_RESUME &&
+ status is UpdateStatus.NeedsInstallPermission &&
+ updateManager.canInstall(context)
+ ) {
+ val needsPermission = status
+ if (needsPermission is UpdateStatus.NeedsInstallPermission) {
+ status = UpdateStatus.ReadyToInstall(needsPermission.apkFile)
+ }
+ }
+ }
+ lifecycleOwner.lifecycle.addObserver(observer)
+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
+ }
+
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Text(
+ text = "App Version & Updates",
+ style = MaterialTheme.typography.titleMedium
+ )
+ Text(
+ text = "Gotcha v${BuildConfig.VERSION_NAME} (build ${BuildConfig.VERSION_CODE})",
+ style = MaterialTheme.typography.bodyMedium
+ )
+
+ when (val currentStatus = status) {
+ is UpdateStatus.Idle -> {
+ Button(onClick = {
+ if (busy) return@Button
+ busy = true
+ scope.launch {
+ try {
+ status = UpdateStatus.Checking
+ status = updateManager.checkForUpdate()
+ } finally {
+ busy = false
+ }
+ }
+ }) {
+ Text("Check for Updates")
+ }
+ }
+ is UpdateStatus.Checking -> {
+ Text(
+ text = "Checking for updates...",
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+ is UpdateStatus.UpToDate -> {
+ Text(
+ text = "Gotcha is up to date (v${currentStatus.currentVersion}).",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.primary
+ )
+ }
+ is UpdateStatus.Available -> {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(
+ text = "New update available: v${currentStatus.info.versionName}",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.primary
+ )
+ if (currentStatus.info.releaseNotes.isNotEmpty()) {
+ Text(
+ text = currentStatus.info.releaseNotes,
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+ Button(onClick = {
+ if (busy) return@Button
+ busy = true
+ scope.launch {
+ try {
+ status = UpdateStatus.Downloading(0)
+ val res = updateManager.downloadUpdate(
+ context,
+ currentStatus.info
+ ) { pct ->
+ status = UpdateStatus.Downloading(pct)
+ }
+ res.onSuccess { apkFile ->
+ status = UpdateStatus.ReadyToInstall(apkFile)
+ }.onFailure { err ->
+ status = UpdateStatus.Error(err.message ?: "Download failed")
+ }
+ } finally {
+ busy = false
+ }
+ }
+ }) {
+ Text("Download Update")
+ }
+ }
+ }
+ is UpdateStatus.Downloading -> {
+ Text(
+ text = "Downloading update: ${currentStatus.progressPercent}%",
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+ is UpdateStatus.ReadyToInstall -> {
+ Button(onClick = {
+ if (!updateManager.installUpdate(context, currentStatus.apkFile)) {
+ status = if (updateManager.canInstall(context)) {
+ UpdateStatus.Error("Could not launch the installer.")
+ } else {
+ UpdateStatus.NeedsInstallPermission(currentStatus.apkFile)
+ }
+ }
+ }) {
+ Text("Install Update")
+ }
+ }
+ is UpdateStatus.NeedsInstallPermission -> {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(
+ text = "Allow Gotcha to install updates from this source, then return here.",
+ style = MaterialTheme.typography.bodySmall
+ )
+ Button(onClick = {
+ updateManager.openInstallPermissionSettings(context)
+ }) {
+ Text("Grant Install Permission")
+ }
+ }
+ }
+ is UpdateStatus.Error -> {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(
+ text = "Error: ${currentStatus.message}",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error
+ )
+ Button(onClick = {
+ if (busy) return@Button
+ busy = true
+ scope.launch {
+ try {
+ status = UpdateStatus.Checking
+ status = updateManager.checkForUpdate()
+ } finally {
+ busy = false
+ }
+ }
+ }) {
+ Text("Retry Check")
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/updater/AppUpdateManager.kt b/app/src/main/java/com/gotcha/updater/AppUpdateManager.kt
new file mode 100644
index 0000000..8c8cc5a
--- /dev/null
+++ b/app/src/main/java/com/gotcha/updater/AppUpdateManager.kt
@@ -0,0 +1,299 @@
+package com.gotcha.updater
+
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.os.Build
+import android.provider.Settings
+import androidx.core.content.FileProvider
+import com.gotcha.BuildConfig
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.suspendCancellableCoroutine
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+import okhttp3.Call
+import okhttp3.Callback
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.Response
+import java.io.File
+import java.io.FileOutputStream
+import java.io.IOException
+import java.security.MessageDigest
+import java.util.concurrent.TimeUnit
+import kotlin.coroutines.resume
+import kotlin.coroutines.resumeWithException
+
+@Serializable
+data class AppUpdateInfo(
+ val versionCode: Int,
+ val versionName: String,
+ val downloadUrl: String,
+ val releaseNotes: String = "",
+ val sha256: String? = null
+)
+
+sealed interface UpdateStatus {
+ data object Idle : UpdateStatus
+ data object Checking : UpdateStatus
+ data class UpToDate(val currentVersion: String) : UpdateStatus
+ data class Available(val info: AppUpdateInfo) : UpdateStatus
+ data class Downloading(val progressPercent: Int) : UpdateStatus
+ data class ReadyToInstall(val apkFile: File) : UpdateStatus
+ data class NeedsInstallPermission(val apkFile: File) : UpdateStatus
+ data class Error(val message: String) : UpdateStatus
+}
+
+/**
+ * In-app updater: reads an update.json manifest, downloads a release APK, and
+ * hands it to PackageInstaller.
+ *
+ * Security model: the manifest and the APK are served over HTTPS from a
+ * repository the user controls. [downloadUpdate] refuses any [AppUpdateInfo.downloadUrl]
+ * that isn't an https URL on the trusted GitHub releases prefix, and when the
+ * manifest pins a [AppUpdateInfo.sha256] the downloaded bytes must match it
+ * before the file is offered for install. PackageInstaller additionally refuses
+ * to update over an existing install signed with a different key.
+ */
+class AppUpdateManager(
+ private val client: OkHttpClient = defaultClient()
+) {
+ companion object {
+ const val DEFAULT_UPDATE_URL =
+ "https://raw.githubusercontent.com/samosa-ai-com/Gotcha/main/update.json"
+
+ const val TRUSTED_DOWNLOAD_HOST = "github.com"
+ const val TRUSTED_DOWNLOAD_PATH_PREFIX = "/samosa-ai-com/Gotcha/releases/download/"
+
+ private val jsonParser = Json { ignoreUnknownKeys = true }
+
+ private fun defaultClient(): OkHttpClient {
+ return OkHttpClient.Builder()
+ .connectTimeout(15, TimeUnit.SECONDS)
+ .readTimeout(30, TimeUnit.SECONDS)
+ .followRedirects(true)
+ .followSslRedirects(true)
+ .build()
+ }
+
+ val shared: AppUpdateManager by lazy { AppUpdateManager() }
+ }
+
+ fun parseUpdateJson(jsonString: String): AppUpdateInfo {
+ return jsonParser.decodeFromString(AppUpdateInfo.serializer(), jsonString)
+ }
+
+ fun isUpdateAvailable(currentVersionCode: Int, remoteInfo: AppUpdateInfo): Boolean {
+ return remoteInfo.versionCode > currentVersionCode
+ }
+
+ /**
+ * Only the manifest-supplied URL is checked (redirects from github.com to the
+ * asset CDN are followed by the client and are not under the attacker's control).
+ */
+ fun isTrustedDownloadUrl(url: String): Boolean = runCatching {
+ val uri = java.net.URI(url)
+ val host = uri.host ?: return false
+ val path = uri.path ?: return false
+ uri.scheme.equals("https", ignoreCase = true) &&
+ host.equals(TRUSTED_DOWNLOAD_HOST, ignoreCase = true) &&
+ path.startsWith(TRUSTED_DOWNLOAD_PATH_PREFIX)
+ }.getOrDefault(false)
+
+ suspend fun checkForUpdate(
+ currentVersionCode: Int = BuildConfig.VERSION_CODE,
+ currentVersionName: String = BuildConfig.VERSION_NAME,
+ manifestUrl: String = DEFAULT_UPDATE_URL
+ ): UpdateStatus = withContext(Dispatchers.IO) {
+ try {
+ val request = Request.Builder()
+ .url(manifestUrl)
+ .build()
+
+ client.awaitResponse(request).use { response ->
+ if (!response.isSuccessful) {
+ return@withContext UpdateStatus.Error("Failed to fetch updates (HTTP ${response.code})")
+ }
+ val bodyText = response.body?.string()
+ ?: return@withContext UpdateStatus.Error("Empty response from update server")
+
+ val remoteInfo = parseUpdateJson(bodyText)
+ if (isUpdateAvailable(currentVersionCode, remoteInfo)) {
+ UpdateStatus.Available(remoteInfo)
+ } else {
+ UpdateStatus.UpToDate(currentVersionName)
+ }
+ }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ UpdateStatus.Error(e.message ?: "Unknown error checking for updates")
+ }
+ }
+
+ suspend fun downloadUpdate(
+ context: Context,
+ updateInfo: AppUpdateInfo,
+ onProgress: (Int) -> Unit = {}
+ ): Result<File> {
+ if (!isTrustedDownloadUrl(updateInfo.downloadUrl)) {
+ return Result.failure(
+ IllegalArgumentException("Untrusted download URL: ${updateInfo.downloadUrl}")
+ )
+ }
+ return downloadUpdateTo(File(context.cacheDir, "updates"), updateInfo, onProgress)
+ }
+
+ /**
+ * Download/verify core, split from [downloadUpdate] so the JVM tests can drive it
+ * against a local server. The trusted-URL gate lives on the public entry point.
+ * [targetDir] must be a directory the FileProvider maps (see res/xml/file_paths.xml).
+ */
+ internal suspend fun downloadUpdateTo(
+ targetDir: File,
+ updateInfo: AppUpdateInfo,
+ onProgress: (Int) -> Unit = {}
+ ): Result<File> = withContext(Dispatchers.IO) {
+ try {
+ val dir = targetDir.apply { mkdirs() }
+ clearStaleApks(dir)
+ val apkFile = File(dir, "gotcha-${updateInfo.versionName}.apk")
+
+ val request = Request.Builder()
+ .url(updateInfo.downloadUrl)
+ .build()
+
+ client.awaitResponse(request).use { response ->
+ if (!response.isSuccessful) {
+ return@withContext Result.failure(
+ RuntimeException("Failed to download APK (HTTP ${response.code})")
+ )
+ }
+
+ val body = response.body
+ ?: return@withContext Result.failure(RuntimeException("APK body is null"))
+
+ val contentLength = body.contentLength()
+ var lastPercent = -1
+ var totalBytesRead = 0L
+
+ body.byteStream().use { input ->
+ FileOutputStream(apkFile).use { output ->
+ val buffer = ByteArray(8192)
+ var bytesRead: Int
+ while (input.read(buffer).also { bytesRead = it } != -1) {
+ output.write(buffer, 0, bytesRead)
+ totalBytesRead += bytesRead
+ if (contentLength > 0) {
+ val percent = ((totalBytesRead * 100) / contentLength).toInt()
+ if (percent != lastPercent) {
+ lastPercent = percent
+ onProgress(percent)
+ }
+ }
+ }
+ }
+ }
+ if (lastPercent != 100) {
+ onProgress(100)
+ }
+
+ updateInfo.sha256?.let { expected ->
+ val actual = sha256Hex(apkFile)
+ if (!actual.equals(expected, ignoreCase = true)) {
+ apkFile.delete()
+ return@withContext Result.failure(
+ IllegalStateException("Downloaded APK failed sha256 verification")
+ )
+ }
+ }
+
+ Result.success(apkFile)
+ }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ Result.failure(e)
+ }
+ }
+
+ fun canInstall(context: Context): Boolean {
+ return Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
+ context.packageManager.canRequestPackageInstalls()
+ }
+
+ fun openInstallPermissionSettings(context: Context) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val settingsIntent = Intent(
+ Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
+ Uri.parse("package:${context.packageName}")
+ ).apply {
+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+ context.startActivity(settingsIntent)
+ }
+ }
+
+ fun installUpdate(context: Context, apkFile: File): Boolean {
+ if (!canInstall(context)) {
+ openInstallPermissionSettings(context)
+ return false
+ }
+
+ return runCatching {
+ val apkUri: Uri = FileProvider.getUriForFile(
+ context,
+ "${context.packageName}.fileprovider",
+ apkFile
+ )
+
+ val installIntent = Intent(Intent.ACTION_VIEW).apply {
+ setDataAndType(apkUri, "application/vnd.android.package-archive")
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+
+ context.startActivity(installIntent)
+ true
+ }.getOrDefault(false)
+ }
+
+ private fun clearStaleApks(dir: File) {
+ dir.listFiles { f -> f.isFile && f.extension == "apk" }
+ ?.forEach { it.delete() }
+ }
+
+ private fun sha256Hex(file: File): String {
+ val digest = MessageDigest.getInstance("SHA-256")
+ file.inputStream().use { input ->
+ val buffer = ByteArray(8192)
+ var read: Int
+ while (input.read(buffer).also { read = it } != -1) {
+ digest.update(buffer, 0, read)
+ }
+ }
+ return digest.digest().joinToString("") { "%02x".format(it) }
+ }
+
+ private suspend fun OkHttpClient.awaitResponse(request: Request): Response =
+ suspendCancellableCoroutine { cont ->
+ val call = newCall(request)
+ cont.invokeOnCancellation { call.cancel() }
+ call.enqueue(object : Callback {
+ override fun onFailure(call: Call, e: IOException) {
+ if (cont.isCancelled) return
+ cont.resumeWithException(e)
+ }
+
+ override fun onResponse(call: Call, response: Response) {
+ if (cont.isCancelled) {
+ response.close()
+ return
+ }
+ cont.resume(response)
+ }
+ })
+ }
+}
diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml
index 7a120b6..d2d9122 100644
--- a/app/src/main/res/xml/file_paths.xml
+++ b/app/src/main/res/xml/file_paths.xml
@@ -6,4 +6,6 @@
<cache-path name="lens" path="lens/" />
<!-- "Share your Gotcha moment" poster PNGs. -->
<cache-path name="poster" path="poster/" />
+ <!-- APK updates downloaded by in-app updater. -->
+ <cache-path name="updates" path="updates/" />
</paths>
diff --git a/app/src/test/java/com/gotcha/updater/AppUpdateManagerRobolectricTest.kt b/app/src/test/java/com/gotcha/updater/AppUpdateManagerRobolectricTest.kt
new file mode 100644
index 0000000..005a507
--- /dev/null
+++ b/app/src/test/java/com/gotcha/updater/AppUpdateManagerRobolectricTest.kt
@@ -0,0 +1,110 @@
+package com.gotcha.updater
+
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.provider.Settings
+import androidx.test.core.app.ApplicationProvider
+import kotlinx.coroutines.test.runTest
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+import org.robolectric.shadows.ShadowApplication
+import java.io.File
+
+/**
+ * Context-dependent updater paths: the trusted-URL gate on the public
+ * [AppUpdateManager.downloadUpdate] entry point and the install-permission flow.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class AppUpdateManagerRobolectricTest {
+
+ private val updateManager = AppUpdateManager()
+ private val context: Context = ApplicationProvider.getApplicationContext()
+
+ @Test
+ fun downloadUpdate_untrustedUrl_returnsFailureBeforeAnyNetworkUse() = runTest {
+ val info = AppUpdateInfo(
+ versionCode = 2,
+ versionName = "1.0.1",
+ downloadUrl = "https://evil.example.com/app.apk"
+ )
+
+ val result = updateManager.downloadUpdate(context, info)
+
+ assertTrue(result.isFailure)
+ assertTrue(result.exceptionOrNull() is IllegalArgumentException)
+ }
+
+ @Test
+ fun downloadUpdate_httpScheme_returnsFailure() = runTest {
+ val info = AppUpdateInfo(
+ versionCode = 2,
+ versionName = "1.0.1",
+ downloadUrl = "http://github.com/samosa-ai-com/Gotcha/releases/download/v1.0.1/app.apk"
+ )
+
+ val result = updateManager.downloadUpdate(context, info)
+
+ assertTrue(result.isFailure)
+ }
+
+ @Test
+ fun installUpdate_withoutInstallPermission_returnsFalseAndOffersSettings() {
+ shadowOf(context.packageManager).setCanRequestPackageInstalls(false)
+ val apkFile = apkInCache()
+
+ val installed = updateManager.installUpdate(context, apkFile)
+
+ assertFalse(installed)
+ val intent = ShadowApplication.getInstance().nextStartedActivity
+ assertEquals(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, intent.action)
+ assertEquals(Uri.parse("package:${context.packageName}"), intent.data)
+ }
+
+ @Test
+ fun installUpdate_withInstallPermission_launchesPackageInstaller() {
+ shadowOf(context.packageManager).setCanRequestPackageInstalls(true)
+ val apkFile = apkInCache()
+
+ val installed = updateManager.installUpdate(context, apkFile)
+
+ assertTrue(installed)
+ val intent = ShadowApplication.getInstance().nextStartedActivity
+ assertEquals(Intent.ACTION_VIEW, intent.action)
+ assertEquals("application/vnd.android.package-archive", intent.type)
+ assertEquals("content", intent.data?.scheme)
+ assertEquals("${context.packageName}.fileprovider", intent.data?.authority)
+ }
+
+ @Test
+ fun installUpdate_apkOutsideFileProviderMapping_returnsFalseInsteadOfCrashing() {
+ shadowOf(context.packageManager).setCanRequestPackageInstalls(true)
+ // File in the cache root, but file_paths.xml only maps cacheDir/updates/.
+ val apkFile = File(context.cacheDir, "gotcha-orphan.apk").apply { writeBytes(byteArrayOf(1)) }
+
+ val installed = updateManager.installUpdate(context, apkFile)
+
+ assertFalse(installed)
+ }
+
+ @Test
+ fun openInstallPermissionSettings_launchesUnknownAppSources() {
+ updateManager.openInstallPermissionSettings(context)
+
+ val intent = ShadowApplication.getInstance().nextStartedActivity
+ assertEquals(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, intent.action)
+ assertEquals(Uri.parse("package:${context.packageName}"), intent.data)
+ }
+
+ private fun apkInCache(): File {
+ val dir = File(context.cacheDir, "updates").apply { mkdirs() }
+ return File(dir, "gotcha-test.apk").apply { writeBytes(byteArrayOf(1, 2, 3)) }
+ }
+}
diff --git a/app/src/test/java/com/gotcha/updater/AppUpdateManagerTest.kt b/app/src/test/java/com/gotcha/updater/AppUpdateManagerTest.kt
new file mode 100644
index 0000000..abf048e
--- /dev/null
+++ b/app/src/test/java/com/gotcha/updater/AppUpdateManagerTest.kt
@@ -0,0 +1,381 @@
+package com.gotcha.updater
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.test.runTest
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import okio.Buffer
+import org.junit.After
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import java.io.File
+import java.security.MessageDigest
+import java.util.concurrent.TimeUnit
+
+class AppUpdateManagerTest {
+
+ private val updateManager = AppUpdateManager()
+
+ private lateinit var server: MockWebServer
+
+ @get:Rule
+ val tempFolder = TemporaryFolder()
+
+ @Before
+ fun setUp() {
+ server = MockWebServer()
+ server.start()
+ }
+
+ @After
+ fun tearDown() {
+ server.shutdown()
+ }
+
+ @Test
+ fun parseUpdateJson_validJson_parsesCorrectly() {
+ val json = """
+ {
+ "versionCode": 2,
+ "versionName": "1.0.1",
+ "downloadUrl": "https://github.com/samosa-ai-com/Gotcha/releases/download/v1.0.1/app-release.apk",
+ "releaseNotes": "Bug fixes"
+ }
+ """.trimIndent()
+
+ val info = updateManager.parseUpdateJson(json)
+
+ assertEquals(2, info.versionCode)
+ assertEquals("1.0.1", info.versionName)
+ assertEquals(
+ "https://github.com/samosa-ai-com/Gotcha/releases/download/v1.0.1/app-release.apk",
+ info.downloadUrl
+ )
+ assertEquals("Bug fixes", info.releaseNotes)
+ assertEquals(null, info.sha256)
+ }
+
+ @Test
+ fun parseUpdateJson_withSha256_parsesIt() {
+ val json = """
+ {
+ "versionCode": 2,
+ "versionName": "1.0.1",
+ "downloadUrl": "https://github.com/samosa-ai-com/Gotcha/releases/download/v1.0.1/app-release.apk",
+ "sha256": "ab12cd34"
+ }
+ """.trimIndent()
+
+ val info = updateManager.parseUpdateJson(json)
+
+ assertEquals("ab12cd34", info.sha256)
+ }
+
+ @Test
+ fun isUpdateAvailable_higherRemoteVersion_returnsTrue() {
+ val info = AppUpdateInfo(
+ versionCode = 2,
+ versionName = "1.0.1",
+ downloadUrl = "https://example.com/app.apk",
+ releaseNotes = "Notes"
+ )
+
+ val result = updateManager.isUpdateAvailable(currentVersionCode = 1, remoteInfo = info)
+
+ assertTrue(result)
+ }
+
+ @Test
+ fun isUpdateAvailable_sameOrLowerRemoteVersion_returnsFalse() {
+ val info = AppUpdateInfo(
+ versionCode = 1,
+ versionName = "1.0.0",
+ downloadUrl = "https://example.com/app.apk",
+ releaseNotes = "Notes"
+ )
+
+ val resultSame = updateManager.isUpdateAvailable(currentVersionCode = 1, remoteInfo = info)
+ val resultHigherLocal = updateManager.isUpdateAvailable(currentVersionCode = 2, remoteInfo = info)
+
+ assertFalse(resultSame)
+ assertFalse(resultHigherLocal)
+ }
+
+ @Test
+ fun isTrustedDownloadUrl_trustedGithubReleasesUrl_returnsTrue() {
+ assertTrue(
+ updateManager.isTrustedDownloadUrl(
+ "https://github.com/samosa-ai-com/Gotcha/releases/download/v1.0.1/app-release.apk"
+ )
+ )
+ }
+
+ @Test
+ fun isTrustedDownloadUrl_httpScheme_returnsFalse() {
+ assertFalse(
+ updateManager.isTrustedDownloadUrl(
+ "http://github.com/samosa-ai-com/Gotcha/releases/download/v1.0.1/app-release.apk"
+ )
+ )
+ }
+
+ @Test
+ fun isTrustedDownloadUrl_otherHost_returnsFalse() {
+ assertFalse(
+ updateManager.isTrustedDownloadUrl(
+ "https://evil.example.com/releases/download/v1.0.1/app-release.apk"
+ )
+ )
+ }
+
+ @Test
+ fun isTrustedDownloadUrl_otherPath_returnsFalse() {
+ assertFalse(
+ updateManager.isTrustedDownloadUrl(
+ "https://github.com/other-org/Gotcha/releases/download/v1.0.1/app-release.apk"
+ )
+ )
+ }
+
+ @Test
+ fun isTrustedDownloadUrl_nonUrl_returnsFalse() {
+ assertFalse(updateManager.isTrustedDownloadUrl("not a url"))
+ }
+
+ @Test
+ fun checkForUpdate_httpError_returnsError() = runTest {
+ server.enqueue(MockResponse().setResponseCode(404))
+
+ val status = updateManager.checkForUpdate(
+ currentVersionCode = 1,
+ currentVersionName = "1.0.0",
+ manifestUrl = server.url("/update.json").toString()
+ )
+
+ assertTrue(status is UpdateStatus.Error)
+ assertTrue((status as UpdateStatus.Error).message.contains("404"))
+ }
+
+ @Test
+ fun checkForUpdate_newerRemoteVersion_returnsAvailable() = runTest {
+ server.enqueue(
+ MockResponse().setResponseCode(200).setBody(
+ """
+ {
+ "versionCode": 2,
+ "versionName": "1.0.1",
+ "downloadUrl": "https://github.com/samosa-ai-com/Gotcha/releases/download/v1.0.1/app-release.apk"
+ }
+ """.trimIndent()
+ )
+ )
+
+ val status = updateManager.checkForUpdate(
+ currentVersionCode = 1,
+ currentVersionName = "1.0.0",
+ manifestUrl = server.url("/update.json").toString()
+ )
+
+ assertTrue(status is UpdateStatus.Available)
+ assertEquals(2, (status as UpdateStatus.Available).info.versionCode)
+ }
+
+ @Test
+ fun checkForUpdate_sameVersion_returnsUpToDate() = runTest {
+ server.enqueue(
+ MockResponse().setResponseCode(200).setBody(
+ """
+ {
+ "versionCode": 1,
+ "versionName": "1.0.0",
+ "downloadUrl": "https://github.com/samosa-ai-com/Gotcha/releases/download/v1.0.0/app-release.apk"
+ }
+ """.trimIndent()
+ )
+ )
+
+ val status = updateManager.checkForUpdate(
+ currentVersionCode = 1,
+ currentVersionName = "1.0.0",
+ manifestUrl = server.url("/update.json").toString()
+ )
+
+ assertTrue(status is UpdateStatus.UpToDate)
+ assertEquals("1.0.0", (status as UpdateStatus.UpToDate).currentVersion)
+ }
+
+ @Test
+ fun checkForUpdate_invalidJson_returnsError() = runTest {
+ server.enqueue(MockResponse().setResponseCode(200).setBody("not json"))
+
+ val status = updateManager.checkForUpdate(
+ currentVersionCode = 1,
+ currentVersionName = "1.0.0",
+ manifestUrl = server.url("/update.json").toString()
+ )
+
+ assertTrue(status is UpdateStatus.Error)
+ }
+
+ @Test
+ fun downloadUpdateTo_success_downloadsFileAndReportsProgress() = runTest {
+ val body = ByteArray(100_000) { 0x41 }
+ server.enqueue(MockResponse().setResponseCode(200).setBody(Buffer().write(body)))
+ val progress = mutableListOf<Int>()
+
+ val result = updateManager.downloadUpdateTo(
+ tempFolder.root,
+ infoFor(server.url("/app.apk").toString()),
+ onProgress = { progress.add(it) }
+ )
+
+ assertTrue(result.isSuccess)
+ val apkFile = result.getOrThrow()
+ assertArrayEquals(body, apkFile.readBytes())
+ assertTrue(progress.isNotEmpty())
+ assertEquals(100, progress.last())
+ }
+
+ @Test
+ fun downloadUpdateTo_progressIsThrottledNotPerChunk() = runTest {
+ val body = ByteArray(2 * 1024 * 1024) { 0x41 }
+ server.enqueue(MockResponse().setResponseCode(200).setBody(Buffer().write(body)))
+ val progress = mutableListOf<Int>()
+
+ val result = updateManager.downloadUpdateTo(
+ tempFolder.root,
+ infoFor(server.url("/app.apk").toString()),
+ onProgress = { progress.add(it) }
+ )
+
+ assertTrue(result.isSuccess)
+ // 8192-byte chunks over 2 MB mean ~245 reads; distinct percents from 0..100 can
+ // never exceed 101, so this proves the callback is throttled to percent changes.
+ assertTrue("progress fired ${progress.size} times", progress.size <= 101)
+ assertEquals(100, progress.last())
+ }
+
+ @Test
+ fun downloadUpdateTo_chunkedBodyWithoutContentLength_stillReports100() = runTest {
+ val body = "apk-bytes".repeat(1000)
+ server.enqueue(MockResponse().setResponseCode(200).setChunkedBody(body, 100))
+ val progress = mutableListOf<Int>()
+
+ val result = updateManager.downloadUpdateTo(
+ tempFolder.root,
+ infoFor(server.url("/app.apk").toString()),
+ onProgress = { progress.add(it) }
+ )
+
+ assertTrue(result.isSuccess)
+ assertEquals(listOf(100), progress)
+ }
+
+ @Test
+ fun downloadUpdateTo_httpError_returnsFailure() = runTest {
+ server.enqueue(MockResponse().setResponseCode(500))
+
+ val result = updateManager.downloadUpdateTo(
+ tempFolder.root,
+ infoFor(server.url("/app.apk").toString())
+ )
+
+ assertTrue(result.isFailure)
+ }
+
+ @Test
+ fun downloadUpdateTo_sha256Matches_succeeds() = runTest {
+ val body = ByteArray(4096) { 0x42 }
+ server.enqueue(MockResponse().setResponseCode(200).setBody(Buffer().write(body)))
+
+ val result = updateManager.downloadUpdateTo(
+ tempFolder.root,
+ infoFor(server.url("/app.apk").toString(), sha256 = sha256Hex(body))
+ )
+
+ assertTrue(result.isSuccess)
+ }
+
+ @Test
+ fun downloadUpdateTo_sha256Mismatch_removesFileAndFails() = runTest {
+ val body = ByteArray(4096) { 0x42 }
+ server.enqueue(MockResponse().setResponseCode(200).setBody(Buffer().write(body)))
+
+ val result = updateManager.downloadUpdateTo(
+ tempFolder.root,
+ infoFor(server.url("/app.apk").toString(), sha256 = "0".repeat(64))
+ )
+
+ assertTrue(result.isFailure)
+ assertTrue(tempFolder.root.listFiles { f -> f.extension == "apk" }.isNullOrEmpty())
+ }
+
+ @Test
+ fun downloadUpdateTo_sha256Absent_skipsVerification() = runTest {
+ val body = ByteArray(4096) { 0x42 }
+ server.enqueue(MockResponse().setResponseCode(200).setBody(Buffer().write(body)))
+
+ val result = updateManager.downloadUpdateTo(
+ tempFolder.root,
+ infoFor(server.url("/app.apk").toString(), sha256 = null)
+ )
+
+ assertTrue(result.isSuccess)
+ }
+
+ @Test
+ fun downloadUpdateTo_staleApksAreCleanedBeforeDownload() = runTest {
+ val stale = File(tempFolder.root, "gotcha-0.9.0.apk").apply { writeBytes(byteArrayOf(1)) }
+ val body = ByteArray(4096) { 0x42 }
+ server.enqueue(MockResponse().setResponseCode(200).setBody(Buffer().write(body)))
+
+ val result = updateManager.downloadUpdateTo(
+ tempFolder.root,
+ infoFor(server.url("/app.apk").toString())
+ )
+
+ assertTrue(result.isSuccess)
+ assertFalse(stale.exists())
+ }
+
+ @Test
+ fun downloadUpdateTo_cancelled_abortsTheDownload() = runTest {
+ server.enqueue(
+ MockResponse()
+ .setResponseCode(200)
+ .setBodyDelay(10, TimeUnit.SECONDS)
+ .setBody("x".repeat(1024))
+ )
+
+ val job = launch(Dispatchers.IO) {
+ updateManager.downloadUpdateTo(
+ tempFolder.root,
+ infoFor(server.url("/app.apk").toString())
+ )
+ }
+ job.cancel()
+ job.join()
+
+ assertTrue(job.isCancelled)
+ }
+
+ private fun infoFor(downloadUrl: String, sha256: String? = null) = AppUpdateInfo(
+ versionCode = 2,
+ versionName = "1.0.1",
+ downloadUrl = downloadUrl,
+ releaseNotes = "Notes",
+ sha256 = sha256
+ )
+
+ private fun sha256Hex(bytes: ByteArray): String {
+ val digest = MessageDigest.getInstance("SHA-256").digest(bytes)
+ return digest.joinToString("") { "%02x".format(it) }
+ }
+}
diff --git a/update.json b/update.json
new file mode 100644
index 0000000..ed02b17
--- /dev/null
+++ b/update.json
@@ -0,0 +1,6 @@
+{
+ "versionCode": 1,
+ "versionName": "1.0.0",
+ "downloadUrl": "https://github.com/samosa-ai-com/Gotcha/releases/download/v1.0.0/app-release.apk",
+ "releaseNotes": ""
+}