feat: in-app self-updating via GitHub Releases, CI/CD pipeline, and R2 config re-fetching
Build & Release Android APK / Build & Publish Release APK (push) Waiting to run

This commit is contained in:
Vaishno Singh
2026-11-18 23:42:22 +05:30
parent 583f421d7f
commit 57b96a21f2
13 changed files with 1094 additions and 9 deletions
@@ -0,0 +1,320 @@
package com.expapp.trigger.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CloudDownload
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.SystemUpdate
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import com.expapp.trigger.update.DownloadState
import com.expapp.trigger.update.ReleaseInfo
import com.expapp.trigger.ui.theme.BgElevated
import com.expapp.trigger.ui.theme.BgSurface
import com.expapp.trigger.ui.theme.BorderDefault
import com.expapp.trigger.ui.theme.BorderSubtle
import com.expapp.trigger.ui.theme.GreenVibrant
import com.expapp.trigger.ui.theme.RedVibrant
import com.expapp.trigger.ui.theme.TextMuted
import com.expapp.trigger.ui.theme.TextPrimary
import com.expapp.trigger.ui.theme.TextSecondary
import java.io.File
@Composable
fun UpdateDialog(
releaseInfo: ReleaseInfo,
currentVersion: String,
downloadState: DownloadState,
onDownload: () -> Unit,
onInstall: (File) -> Unit,
onDismiss: () -> Unit
) {
Dialog(onDismissRequest = {
if (downloadState !is DownloadState.Downloading) {
onDismiss()
}
}) {
Box(
modifier = Modifier
.clip(RoundedCornerShape(24.dp))
.background(
brush = Brush.verticalGradient(
listOf(Color(0xFF0C1420), Color(0xFF070B12))
)
)
.border(1.dp, GreenVibrant.copy(alpha = 0.35f), RoundedCornerShape(24.dp))
.padding(24.dp)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
// Header Icon
Box(
modifier = Modifier
.size(60.dp)
.background(
brush = Brush.radialGradient(
listOf(GreenVibrant.copy(alpha = 0.22f), Color.Transparent)
),
shape = CircleShape
)
.border(1.dp, GreenVibrant.copy(alpha = 0.45f), CircleShape),
contentAlignment = Alignment.Center
) {
Icon(
imageVector = Icons.Default.SystemUpdate,
contentDescription = "Update",
tint = GreenVibrant,
modifier = Modifier.size(28.dp)
)
}
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "Update Available",
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
color = TextPrimary
)
Spacer(modifier = Modifier.height(6.dp))
// Version Badge row: v1.0 -> v1.1
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = "v$currentVersion",
fontSize = 12.sp,
color = TextMuted,
fontFamily = FontFamily.Monospace,
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.background(BgElevated)
.border(1.dp, BorderSubtle, RoundedCornerShape(8.dp))
.padding(horizontal = 8.dp, vertical = 3.dp)
)
Text("→", fontSize = 14.sp, color = GreenVibrant, fontWeight = FontWeight.Bold)
Text(
text = releaseInfo.tagName,
fontSize = 12.sp,
color = GreenVibrant,
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Monospace,
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.background(GreenVibrant.copy(alpha = 0.12f))
.border(1.dp, GreenVibrant.copy(alpha = 0.4f), RoundedCornerShape(8.dp))
.padding(horizontal = 8.dp, vertical = 3.dp)
)
if (releaseInfo.sizeBytes > 0) {
val mb = String.format("%.1f MB", releaseInfo.sizeBytes / (1024.0 * 1024.0))
Text(
text = mb,
fontSize = 11.sp,
color = TextSecondary,
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.background(BgElevated)
.border(1.dp, BorderSubtle, RoundedCornerShape(8.dp))
.padding(horizontal = 6.dp, vertical = 3.dp)
)
}
}
Spacer(modifier = Modifier.height(16.dp))
// Changelog Card
Text(
text = "WHAT'S NEW",
fontSize = 11.sp,
fontWeight = FontWeight.SemiBold,
color = TextMuted,
letterSpacing = 1.sp,
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(6.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 140.dp)
.clip(RoundedCornerShape(14.dp))
.background(BgElevated)
.border(1.dp, BorderDefault, RoundedCornerShape(14.dp))
.padding(14.dp)
.verticalScroll(rememberScrollState())
) {
val changelogText = if (releaseInfo.changelog.isNotBlank()) {
releaseInfo.changelog.trim()
} else {
"• Performance improvements & new features."
}
Text(
text = changelogText,
fontSize = 13.sp,
color = TextSecondary,
lineHeight = 18.sp
)
}
Spacer(modifier = Modifier.height(16.dp))
// Download Progress / States
when (downloadState) {
is DownloadState.Downloading -> {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = "Downloading update…",
fontSize = 12.sp,
color = TextSecondary
)
Text(
text = "${downloadState.progressPercent}%",
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
color = GreenVibrant
)
}
Spacer(modifier = Modifier.height(8.dp))
LinearProgressIndicator(
progress = { downloadState.progressPercent / 100f },
modifier = Modifier
.fillMaxWidth()
.height(8.dp)
.clip(RoundedCornerShape(4.dp)),
color = GreenVibrant,
trackColor = GreenVibrant.copy(alpha = 0.15f)
)
if (downloadState.totalBytes > 0) {
Spacer(modifier = Modifier.height(6.dp))
val downloadedMb = String.format("%.1f", downloadState.bytesDownloaded / (1024.0 * 1024.0))
val totalMb = String.format("%.1f MB", downloadState.totalBytes / (1024.0 * 1024.0))
Text(
text = "$downloadedMb / $totalMb",
fontSize = 11.sp,
color = TextMuted
)
}
}
}
is DownloadState.Failed -> {
Text(
text = downloadState.error,
fontSize = 12.sp,
color = RedVibrant,
modifier = Modifier.padding(vertical = 4.dp)
)
}
else -> {}
}
Spacer(modifier = Modifier.height(20.dp))
// Actions row
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
TextButton(
onClick = onDismiss,
enabled = downloadState !is DownloadState.Downloading,
modifier = Modifier
.weight(1f)
.clip(RoundedCornerShape(14.dp))
.background(BgElevated)
.border(1.dp, BorderDefault, RoundedCornerShape(14.dp))
) {
Text(
"Later",
color = TextSecondary,
fontWeight = FontWeight.Medium
)
}
Button(
onClick = {
when (downloadState) {
is DownloadState.ReadyToInstall -> onInstall(downloadState.apkFile)
is DownloadState.Downloading -> {}
else -> onDownload()
}
},
enabled = downloadState !is DownloadState.Downloading,
shape = RoundedCornerShape(14.dp),
colors = ButtonDefaults.buttonColors(
containerColor = GreenVibrant.copy(alpha = 0.2f),
contentColor = GreenVibrant
),
modifier = Modifier.weight(1.3f)
) {
Row(verticalAlignment = Alignment.CenterVertically) {
val icon = when (downloadState) {
is DownloadState.ReadyToInstall -> Icons.Default.SystemUpdate
else -> Icons.Default.Download
}
val text = when (downloadState) {
is DownloadState.ReadyToInstall -> "Install Now"
is DownloadState.Failed -> "Retry"
is DownloadState.Downloading -> "Downloading…"
else -> "Update Now"
}
Icon(icon, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(modifier = Modifier.width(6.dp))
Text(
text = text,
fontWeight = FontWeight.Bold,
fontSize = 14.sp
)
}
}
}
}
}
}
}
@@ -29,19 +29,25 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CloudSync
import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.PowerOff
import androidx.compose.material.icons.filled.PowerSettingsNew
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.RestartAlt
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -58,6 +64,8 @@ import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.expapp.trigger.data.model.DeviceConfig
@@ -66,6 +74,7 @@ import com.expapp.trigger.network.TriggerAction
import com.expapp.trigger.ui.components.ActionConfirmDialog
import com.expapp.trigger.ui.components.HugeActionButton
import com.expapp.trigger.ui.components.StatusBanner
import com.expapp.trigger.ui.theme.AmberVibrant
import com.expapp.trigger.ui.theme.BgElevated
import com.expapp.trigger.ui.theme.BgSurface
import com.expapp.trigger.ui.theme.BorderDefault
@@ -100,10 +109,111 @@ fun DevicePage(
onRefreshStatus: () -> Unit,
onTrigger: (TriggerAction) -> Unit,
onDelete: (DeviceConfig) -> Unit,
onSyncConfig: () -> Unit = {},
onUpdateDevice: (DeviceConfig) -> Unit = {},
modifier: Modifier = Modifier
) {
var pendingAction by remember { mutableStateOf<TriggerAction?>(null) }
var showDeleteConfirm by remember { mutableStateOf(false) }
var showEditDialog by remember { mutableStateOf(false) }
if (showEditDialog) {
var editName by remember { mutableStateOf(device.name) }
var editNode by remember { mutableStateOf(device.node) }
var editR2Url by remember { mutableStateOf(device.r2Url) }
var editSecretKey by remember { mutableStateOf(device.secretKey) }
var showKey by remember { mutableStateOf(false) }
val editFieldColors = OutlinedTextFieldDefaults.colors(
focusedBorderColor = GreenVibrant,
unfocusedBorderColor = BorderDefault,
focusedLabelColor = GreenVibrant,
unfocusedLabelColor = TextSecondary,
cursorColor = GreenVibrant,
focusedTextColor = TextPrimary,
unfocusedTextColor = TextPrimary
)
AlertDialog(
onDismissRequest = { showEditDialog = false },
containerColor = BgSurface,
shape = RoundedCornerShape(20.dp),
title = { Text("Edit Device", color = TextPrimary, fontWeight = FontWeight.Bold) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = editName,
onValueChange = { editName = it },
label = { Text("Device Name") },
singleLine = true,
colors = editFieldColors,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.fillMaxWidth()
)
OutlinedTextField(
value = editNode,
onValueChange = { editNode = it },
label = { Text("Node Identifier") },
singleLine = true,
colors = editFieldColors,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.fillMaxWidth()
)
OutlinedTextField(
value = editR2Url,
onValueChange = { editR2Url = it },
label = { Text("Cloudflare R2 JSON URL") },
singleLine = true,
colors = editFieldColors,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.fillMaxWidth()
)
OutlinedTextField(
value = editSecretKey,
onValueChange = { editSecretKey = it },
label = { Text("Secret Key") },
trailingIcon = {
IconButton(onClick = { showKey = !showKey }) {
Icon(
if (showKey) Icons.Default.VisibilityOff else Icons.Default.Visibility,
null,
tint = TextSecondary
)
}
},
visualTransformation = if (showKey) VisualTransformation.None else PasswordVisualTransformation(),
singleLine = true,
colors = editFieldColors,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.fillMaxWidth()
)
}
},
confirmButton = {
Button(
onClick = {
showEditDialog = false
val updated = device.copy(
name = editName.trim().ifBlank { device.name },
node = editNode.trim().ifBlank { device.node },
r2Url = editR2Url.trim(),
secretKey = editSecretKey.trim()
)
onUpdateDevice(updated)
},
colors = ButtonDefaults.buttonColors(containerColor = GreenVibrant.copy(alpha = 0.2f)),
shape = RoundedCornerShape(12.dp)
) {
Text("Save", color = GreenVibrant, fontWeight = FontWeight.Bold)
}
},
dismissButton = {
TextButton(onClick = { showEditDialog = false }) {
Text("Cancel", color = TextSecondary)
}
}
)
}
if (pendingAction != null) {
ActionConfirmDialog(
@@ -274,6 +384,44 @@ fun DevicePage(
}
}
// Re-fetch R2 JSON config button
IconButton(
onClick = onSyncConfig,
modifier = Modifier
.size(36.dp)
.clip(RoundedCornerShape(10.dp))
.background(AmberVibrant.copy(alpha = 0.08f))
.border(1.dp, AmberVibrant.copy(alpha = 0.2f), RoundedCornerShape(10.dp))
) {
Icon(
imageVector = Icons.Default.CloudSync,
contentDescription = "Re-fetch R2 JSON",
tint = AmberVibrant,
modifier = Modifier.size(18.dp)
)
}
Spacer(modifier = Modifier.width(6.dp))
// Edit device button
IconButton(
onClick = { showEditDialog = true },
modifier = Modifier
.size(36.dp)
.clip(RoundedCornerShape(10.dp))
.background(BorderSubtle.copy(alpha = 0.3f))
.border(1.dp, BorderSubtle, RoundedCornerShape(10.dp))
) {
Icon(
imageVector = Icons.Default.Edit,
contentDescription = "Edit device",
tint = TextSecondary,
modifier = Modifier.size(18.dp)
)
}
Spacer(modifier = Modifier.width(6.dp))
// Refresh button (spins while checking)
IconButton(
onClick = { if (!isCheckingStatus) onRefreshStatus() },
@@ -7,6 +7,7 @@ import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
@@ -24,6 +25,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.SystemUpdate
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
@@ -53,12 +55,15 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.expapp.trigger.BuildConfig
import com.expapp.trigger.data.model.DeviceConfig
import com.expapp.trigger.data.repository.DeviceRepository
import com.expapp.trigger.network.NodeStatus
import com.expapp.trigger.network.TriggerAction
import com.expapp.trigger.network.TriggerClient
import com.expapp.trigger.ui.components.UpdateDialog
import com.expapp.trigger.ui.theme.BgBase
import com.expapp.trigger.ui.theme.BgElevated
import com.expapp.trigger.ui.theme.BgSurface
import com.expapp.trigger.ui.theme.BorderSubtle
import com.expapp.trigger.ui.theme.GreenVibrant
@@ -68,6 +73,10 @@ import com.expapp.trigger.ui.theme.OnlineText
import com.expapp.trigger.ui.theme.TextMuted
import com.expapp.trigger.ui.theme.TextPrimary
import com.expapp.trigger.ui.theme.TextSecondary
import com.expapp.trigger.update.DownloadState
import com.expapp.trigger.update.ReleaseInfo
import com.expapp.trigger.update.UpdateCheckResult
import com.expapp.trigger.update.UpdateManager
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
@@ -98,6 +107,35 @@ fun MainScreen(
onDispose { lifecycleOwner.lifecycle.removeObserver(obs) }
}
val updateManager = remember { UpdateManager(context) }
var availableUpdate by remember { mutableStateOf<ReleaseInfo?>(null) }
var showUpdateDialog by remember { mutableStateOf(false) }
var downloadState by remember { mutableStateOf<DownloadState>(DownloadState.Idle) }
var isCheckingUpdate by remember { mutableStateOf(false) }
fun checkAppUpdate(showToast: Boolean = false) {
isCheckingUpdate = true
updateManager.checkForUpdate(BuildConfig.VERSION_NAME) { result ->
isCheckingUpdate = false
when (result) {
is UpdateCheckResult.UpdateAvailable -> {
availableUpdate = result.info
showUpdateDialog = true
}
is UpdateCheckResult.UpToDate -> {
if (showToast) {
Toast.makeText(context, "App is up to date (v${BuildConfig.VERSION_NAME})", Toast.LENGTH_SHORT).show()
}
}
is UpdateCheckResult.Error -> {
if (showToast) {
Toast.makeText(context, "Update check failed: ${result.message}", Toast.LENGTH_SHORT).show()
}
}
}
}
}
val loadingStates = remember { mutableStateMapOf<String, Boolean>() }
val statusStates = remember { mutableStateMapOf<String, Pair<String, Boolean>>() }
val nodeStatuses = remember { mutableStateMapOf<String, NodeStatus>() }
@@ -116,11 +154,18 @@ fun MainScreen(
fun syncEndpoints(showToast: Boolean = false) {
val current = repository.getDevices()
if (current.isEmpty()) return
if (current.isEmpty()) {
checkAppUpdate(showToast)
return
}
isSyncing = true
var updated = 0; var completed = 0
val total = current.count { it.r2Url.isNotBlank() }
if (total == 0) { isSyncing = false; return }
if (total == 0) {
isSyncing = false
checkAppUpdate(showToast)
return
}
current.filter { it.r2Url.isNotBlank() }.forEach { device ->
triggerClient.fetchR2Config(device.r2Url) { result ->
completed++
@@ -135,13 +180,17 @@ fun MainScreen(
if (updated > 0) "Endpoints updated" else "Already up to date",
Toast.LENGTH_SHORT
).show()
checkAppUpdate(showToast)
}
}
}
}
// Initial R2 sync on launch
LaunchedEffect(Unit) { syncEndpoints(false) }
// Initial R2 sync and update check on launch
LaunchedEffect(Unit) {
syncEndpoints(false)
checkAppUpdate(false)
}
// Active 5-second polling — only while in foreground on a device page
LaunchedEffect(pagerState.currentPage, isAppInForeground, devices.size) {
@@ -232,6 +281,27 @@ fun MainScreen(
}
},
actions = {
if (availableUpdate != null) {
Row(
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.background(GreenVibrant.copy(alpha = 0.15f))
.border(1.dp, GreenVibrant.copy(alpha = 0.4f), RoundedCornerShape(8.dp))
.clickable { showUpdateDialog = true }
.padding(horizontal = 8.dp, vertical = 5.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(Icons.Default.SystemUpdate, null, tint = GreenVibrant, modifier = Modifier.size(13.dp))
Spacer(modifier = Modifier.width(4.dp))
Text(
"v${availableUpdate!!.versionName}",
color = GreenVibrant,
fontSize = 11.sp,
fontWeight = FontWeight.Bold
)
}
Spacer(modifier = Modifier.width(4.dp))
}
IconButton(onClick = { syncEndpoints(true) }, enabled = !isSyncing) {
Icon(
Icons.Default.Refresh,
@@ -299,7 +369,36 @@ fun MainScreen(
onDismissStatus = { statusStates.remove(dev.id) },
onRefreshStatus = { refreshStatus(dev, showIndicator = true) },
onTrigger = { action -> executeAction(dev, action) },
onDelete = { d -> repository.deleteDevice(d.id); devices = repository.getDevices() }
onDelete = { d -> repository.deleteDevice(d.id); devices = repository.getDevices() },
onSyncConfig = {
triggerClient.fetchR2Config(dev.r2Url) { result ->
result.onSuccess { ep ->
val changed = repository.updateEndpoints(dev.id, ep.powerOn, ep.powerOff, ep.reboot, ep.status)
devices = repository.getDevices()
val msg = if (changed) "Endpoints updated from R2" else "Endpoints already up to date"
statusStates[dev.id] = msg to true
refreshStatus(dev, showIndicator = true)
}.onFailure { ex ->
statusStates[dev.id] = "Failed to fetch R2: ${ex.message}" to false
}
}
},
onUpdateDevice = { updated ->
repository.updateDevice(updated)
devices = repository.getDevices()
if (updated.r2Url.isNotBlank() && updated.r2Url != dev.r2Url) {
triggerClient.fetchR2Config(updated.r2Url) { result ->
result.onSuccess { ep ->
repository.updateEndpoints(updated.id, ep.powerOn, ep.powerOff, ep.reboot, ep.status)
devices = repository.getDevices()
statusStates[updated.id] = "Device & endpoints updated" to true
refreshStatus(updated, showIndicator = true)
}
}
} else {
statusStates[updated.id] = "Device updated" to true
}
}
)
} else {
AddDevicePage(
@@ -317,4 +416,24 @@ fun MainScreen(
}
}
}
if (showUpdateDialog && availableUpdate != null) {
UpdateDialog(
releaseInfo = availableUpdate!!,
currentVersion = BuildConfig.VERSION_NAME,
downloadState = downloadState,
onDownload = {
downloadState = DownloadState.Downloading(0, 0, availableUpdate!!.sizeBytes)
updateManager.downloadApk(availableUpdate!!.downloadUrl) { state ->
downloadState = state
}
},
onInstall = { file ->
updateManager.installApk(file)
},
onDismiss = {
showUpdateDialog = false
}
)
}
}
@@ -0,0 +1,285 @@
package com.expapp.trigger.update
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import androidx.core.content.FileProvider
import com.google.gson.JsonParser
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.util.concurrent.TimeUnit
class UpdateManager(
private val context: Context,
private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build(),
val githubRepo: String = "vaishnosingh/server-control-app"
) {
private val mainHandler = try {
val looper = Looper.getMainLooper()
if (looper != null) Handler(looper) else null
} catch (e: Throwable) {
null
}
private fun runOnMain(block: () -> Unit) {
mainHandler?.post(block) ?: block()
}
/**
* Checks GitHub Releases API for the latest published release.
*/
fun checkForUpdate(
currentVersionName: String,
callback: (UpdateCheckResult) -> Unit
) {
val url = "https://api.github.com/repos/$githubRepo/releases/latest"
val request = Request.Builder()
.url(url)
.addHeader("Accept", "application/vnd.github.v3+json")
.addHeader("User-Agent", "ServerControlApp")
.get()
.build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
runOnMain {
callback(UpdateCheckResult.Error("Network error: ${e.localizedMessage}"))
}
}
override fun onResponse(call: Call, response: Response) {
response.use { res ->
if (res.code == 404) {
runOnMain { callback(UpdateCheckResult.UpToDate) }
return
}
if (!res.isSuccessful) {
runOnMain {
callback(UpdateCheckResult.Error("HTTP ${res.code}: Unable to check updates"))
}
return
}
val body = res.body?.string().orEmpty()
try {
val json = JsonParser.parseString(body).asJsonObject
val tagName = json.get("tag_name")?.asString.orEmpty()
val title = json.get("name")?.asString?.ifBlank { tagName } ?: tagName
val changelog = json.get("body")?.asString.orEmpty()
val assets = json.getAsJsonArray("assets")
var apkUrl: String? = null
var apkName = "app-release.apk"
var apkSize = 0L
if (assets != null) {
for (element in assets) {
val assetObj = element.asJsonObject
val name = assetObj.get("name")?.asString.orEmpty()
if (name.endsWith(".apk", ignoreCase = true)) {
apkUrl = assetObj.get("browser_download_url")?.asString
apkName = name
apkSize = assetObj.get("size")?.asLong ?: 0L
break
}
}
}
if (apkUrl.isNullOrBlank()) {
runOnMain { callback(UpdateCheckResult.UpToDate) }
return
}
val cleanRemoteVersion = tagName.removePrefix("v").removePrefix("V").trim()
val cleanLocalVersion = currentVersionName.removePrefix("v").removePrefix("V").trim()
if (isNewerVersion(cleanRemoteVersion, cleanLocalVersion)) {
val releaseInfo = ReleaseInfo(
tagName = tagName,
versionName = cleanRemoteVersion,
title = title,
changelog = changelog,
downloadUrl = apkUrl,
apkFileName = apkName,
sizeBytes = apkSize
)
runOnMain {
callback(UpdateCheckResult.UpdateAvailable(releaseInfo))
}
} else {
runOnMain { callback(UpdateCheckResult.UpToDate) }
}
} catch (e: Exception) {
runOnMain {
callback(UpdateCheckResult.Error("Failed to parse update info: ${e.message}"))
}
}
}
}
})
}
/**
* Downloads the APK file to the app's cache directory and streams progress updates.
*/
fun downloadApk(
downloadUrl: String,
onProgress: (DownloadState) -> Unit
): Call {
val request = Request.Builder()
.url(downloadUrl)
.addHeader("User-Agent", "ServerControlApp")
.get()
.build()
val call = okHttpClient.newCall(request)
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
if (!call.isCanceled()) {
runOnMain {
onProgress(DownloadState.Failed("Download failed: ${e.localizedMessage}"))
}
}
}
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) {
runOnMain {
onProgress(DownloadState.Failed("Server returned HTTP ${response.code}"))
}
return
}
val responseBody = response.body
if (responseBody == null) {
runOnMain {
onProgress(DownloadState.Failed("Response body was empty"))
}
return
}
val updateDir = File(context.cacheDir, "updates")
if (!updateDir.exists()) {
updateDir.mkdirs()
}
val apkFile = File(updateDir, "update.apk")
if (apkFile.exists()) {
apkFile.delete()
}
try {
val totalBytes = responseBody.contentLength()
var bytesDownloaded = 0L
responseBody.byteStream().use { input ->
FileOutputStream(apkFile).use { output ->
val buffer = ByteArray(8192)
var read: Int
var lastPercent = -1
while (input.read(buffer).also { read = it } != -1) {
if (call.isCanceled()) return
output.write(buffer, 0, read)
bytesDownloaded += read
val percent = if (totalBytes > 0) {
((bytesDownloaded * 100) / totalBytes).toInt()
} else 0
if (percent != lastPercent) {
lastPercent = percent
runOnMain {
onProgress(
DownloadState.Downloading(
progressPercent = percent,
bytesDownloaded = bytesDownloaded,
totalBytes = totalBytes
)
)
}
}
}
output.flush()
}
}
runOnMain {
onProgress(DownloadState.ReadyToInstall(apkFile))
}
} catch (e: Exception) {
if (!call.isCanceled()) {
runOnMain {
onProgress(DownloadState.Failed("File write failed: ${e.localizedMessage}"))
}
}
}
}
})
return call
}
/**
* Prompts Android package installer to install the downloaded APK.
*/
fun installApk(apkFile: File) {
if (!apkFile.exists()) return
// On Android 8.0+, check if installing from unknown sources is permitted
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!context.packageManager.canRequestPackageInstalls()) {
val settingsIntent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).apply {
data = Uri.parse("package:${context.packageName}")
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
context.startActivity(settingsIntent)
return
}
}
val apkUri = FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
apkFile
)
val installIntent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(apkUri, "application/vnd.android.package-archive")
flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK
}
context.startActivity(installIntent)
}
companion object {
/**
* Semantic version comparator. Returns true if remote is strictly greater than local.
*/
fun isNewerVersion(remote: String, local: String): Boolean {
val remoteParts = remote.split("-")[0].split(".").mapNotNull { it.toIntOrNull() }
val localParts = local.split("-")[0].split(".").mapNotNull { it.toIntOrNull() }
val maxLen = maxOf(remoteParts.size, localParts.size)
for (i in 0 until maxLen) {
val r = remoteParts.getOrElse(i) { 0 }
val l = localParts.getOrElse(i) { 0 }
if (r > l) return true
if (r < l) return false
}
return false
}
}
}
@@ -0,0 +1,30 @@
package com.expapp.trigger.update
import java.io.File
data class ReleaseInfo(
val tagName: String,
val versionName: String,
val title: String,
val changelog: String,
val downloadUrl: String,
val apkFileName: String,
val sizeBytes: Long
)
sealed class UpdateCheckResult {
data class UpdateAvailable(val info: ReleaseInfo) : UpdateCheckResult()
object UpToDate : UpdateCheckResult()
data class Error(val message: String) : UpdateCheckResult()
}
sealed class DownloadState {
object Idle : DownloadState()
data class Downloading(
val progressPercent: Int,
val bytesDownloaded: Long,
val totalBytes: Long
) : DownloadState()
data class ReadyToInstall(val apkFile: File) : DownloadState()
data class Failed(val error: String) : DownloadState()
}