4 Commits
6 changed files with 205 additions and 80 deletions
+6 -1
View File
@@ -47,9 +47,14 @@ jobs:
elif [[ "${{ github.ref }}" == refs/tags/v* ]]; then elif [[ "${{ github.ref }}" == refs/tags/v* ]]; then
TAG="${GITHUB_REF#refs/tags/}" TAG="${GITHUB_REF#refs/tags/}"
else else
# On pushes to main, generate a version based on run number # Extract versionName from app/build.gradle.kts
APP_VERSION=$(grep 'versionName = ' app/build.gradle.kts | head -n 1 | cut -d '"' -f 2)
if [ -n "$APP_VERSION" ]; then
TAG="v$APP_VERSION"
else
TAG="v1.0.${{ github.run_number }}" TAG="v1.0.${{ github.run_number }}"
fi fi
fi
echo "TAG=$TAG" >> $GITHUB_OUTPUT echo "TAG=$TAG" >> $GITHUB_OUTPUT
echo "Release tag will be $TAG" echo "Release tag will be $TAG"
+2 -2
View File
@@ -11,8 +11,8 @@ android {
applicationId = "com.expapp.trigger" applicationId = "com.expapp.trigger"
minSdk = 24 minSdk = 24
targetSdk = 34 targetSdk = 34
versionCode = 1 versionCode = 3
versionName = "1.0" versionName = "1.0.3"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables { vectorDrawables {
+4
View File
@@ -31,6 +31,10 @@
android:name="android.support.FILE_PROVIDER_PATHS" android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" /> android:resource="@xml/file_paths" />
</provider> </provider>
<receiver
android:name=".update.InstallStatusReceiver"
android:exported="false" />
</application> </application>
</manifest> </manifest>
@@ -27,7 +27,7 @@ import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.SystemUpdate import androidx.compose.material.icons.filled.SystemUpdate
import androidx.compose.material.icons.filled.Terminal import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
@@ -110,6 +110,7 @@ fun MainScreen(
val updateManager = remember { UpdateManager(context) } val updateManager = remember { UpdateManager(context) }
var availableUpdate by remember { mutableStateOf<ReleaseInfo?>(null) } var availableUpdate by remember { mutableStateOf<ReleaseInfo?>(null) }
var showUpdateDialog by remember { mutableStateOf(false) } var showUpdateDialog by remember { mutableStateOf(false) }
var dismissedVersion by remember { mutableStateOf<String?>(null) }
var downloadState by remember { mutableStateOf<DownloadState>(DownloadState.Idle) } var downloadState by remember { mutableStateOf<DownloadState>(DownloadState.Idle) }
var isCheckingUpdate by remember { mutableStateOf(false) } var isCheckingUpdate by remember { mutableStateOf(false) }
@@ -120,8 +121,10 @@ fun MainScreen(
when (result) { when (result) {
is UpdateCheckResult.UpdateAvailable -> { is UpdateCheckResult.UpdateAvailable -> {
availableUpdate = result.info availableUpdate = result.info
if (showToast || dismissedVersion != result.info.versionName) {
showUpdateDialog = true showUpdateDialog = true
} }
}
is UpdateCheckResult.UpToDate -> { is UpdateCheckResult.UpToDate -> {
if (showToast) { if (showToast) {
Toast.makeText(context, "App is up to date (v${BuildConfig.VERSION_NAME})", Toast.LENGTH_SHORT).show() Toast.makeText(context, "App is up to date (v${BuildConfig.VERSION_NAME})", Toast.LENGTH_SHORT).show()
@@ -154,16 +157,12 @@ fun MainScreen(
fun syncEndpoints(showToast: Boolean = false) { fun syncEndpoints(showToast: Boolean = false) {
val current = repository.getDevices() val current = repository.getDevices()
if (current.isEmpty()) { if (current.isEmpty()) return
checkAppUpdate(showToast)
return
}
isSyncing = true isSyncing = true
var updated = 0; var completed = 0 var updated = 0; var completed = 0
val total = current.count { it.r2Url.isNotBlank() } val total = current.count { it.r2Url.isNotBlank() }
if (total == 0) { if (total == 0) {
isSyncing = false isSyncing = false
checkAppUpdate(showToast)
return return
} }
current.filter { it.r2Url.isNotBlank() }.forEach { device -> current.filter { it.r2Url.isNotBlank() }.forEach { device ->
@@ -180,7 +179,6 @@ fun MainScreen(
if (updated > 0) "Endpoints updated" else "Already up to date", if (updated > 0) "Endpoints updated" else "Already up to date",
Toast.LENGTH_SHORT Toast.LENGTH_SHORT
).show() ).show()
checkAppUpdate(showToast)
} }
} }
} }
@@ -241,33 +239,37 @@ fun MainScreen(
modifier = modifier.fillMaxSize(), modifier = modifier.fillMaxSize(),
containerColor = BgBase, containerColor = BgBase,
topBar = { topBar = {
CenterAlignedTopAppBar( TopAppBar(
title = { title = {
Row(verticalAlignment = Alignment.CenterVertically) { Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(start = 2.dp)
) {
Icon( Icon(
Icons.Default.Terminal, Icons.Default.Terminal,
contentDescription = null, contentDescription = null,
tint = GreenVibrant, tint = GreenVibrant,
modifier = Modifier.size(18.dp) modifier = Modifier.size(18.dp)
) )
Spacer(modifier = Modifier.width(10.dp)) Spacer(modifier = Modifier.width(8.dp))
Text( Text(
text = "DEVICE TRIGGER", text = "DEVICE TRIGGER",
fontSize = 14.sp, fontSize = 13.sp,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Bold,
letterSpacing = 2.sp, letterSpacing = 1.5.sp,
color = TextPrimary, color = TextPrimary,
fontFamily = FontFamily.Monospace fontFamily = FontFamily.Monospace,
maxLines = 1
) )
val onlineCount = devices.count { nodeStatuses[it.id]?.isOnline == true } val onlineCount = devices.count { nodeStatuses[it.id]?.isOnline == true }
if (devices.isNotEmpty() && onlineCount > 0) { if (devices.isNotEmpty() && onlineCount > 0) {
Spacer(modifier = Modifier.width(10.dp)) Spacer(modifier = Modifier.width(8.dp))
Box( Box(
modifier = Modifier modifier = Modifier
.clip(CircleShape) .clip(CircleShape)
.background(OnlineBg) .background(OnlineBg)
.border(1.dp, OnlineBorder, CircleShape) .border(1.dp, OnlineBorder, CircleShape)
.padding(horizontal = 8.dp, vertical = 2.dp) .padding(horizontal = 7.dp, vertical = 2.dp)
) { ) {
Text( Text(
"$onlineCount online", "$onlineCount online",
@@ -282,27 +284,31 @@ fun MainScreen(
}, },
actions = { actions = {
if (availableUpdate != null) { if (availableUpdate != null) {
Row( IconButton(
modifier = Modifier onClick = { showUpdateDialog = true },
.clip(RoundedCornerShape(8.dp)) modifier = Modifier.size(40.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)) Box(contentAlignment = Alignment.TopEnd) {
Spacer(modifier = Modifier.width(4.dp)) Icon(
Text( Icons.Default.SystemUpdate,
"v${availableUpdate!!.versionName}", contentDescription = "Update available",
color = GreenVibrant, tint = GreenVibrant,
fontSize = 11.sp, modifier = Modifier.size(20.dp)
fontWeight = FontWeight.Bold )
Box(
modifier = Modifier
.size(7.dp)
.background(GreenVibrant, CircleShape)
.border(1.dp, BgSurface, CircleShape)
) )
} }
Spacer(modifier = Modifier.width(4.dp))
} }
IconButton(onClick = { syncEndpoints(true) }, enabled = !isSyncing) { }
IconButton(
onClick = { syncEndpoints(true) },
enabled = !isSyncing,
modifier = Modifier.size(40.dp)
) {
Icon( Icon(
Icons.Default.Refresh, Icons.Default.Refresh,
"Sync", "Sync",
@@ -311,12 +317,13 @@ fun MainScreen(
) )
} }
IconButton( IconButton(
onClick = { coroutineScope.launch { pagerState.animateScrollToPage(devices.size) } } onClick = { coroutineScope.launch { pagerState.animateScrollToPage(devices.size) } },
modifier = Modifier.size(40.dp)
) { ) {
Icon(Icons.Default.Add, "Add Device", tint = GreenVibrant) Icon(Icons.Default.Add, "Add Device", tint = GreenVibrant)
} }
}, },
colors = TopAppBarDefaults.centerAlignedTopAppBarColors( colors = TopAppBarDefaults.topAppBarColors(
containerColor = BgSurface containerColor = BgSurface
) )
) )
@@ -429,9 +436,11 @@ fun MainScreen(
} }
}, },
onInstall = { file -> onInstall = { file ->
showUpdateDialog = false
updateManager.installApk(file) updateManager.installApk(file)
}, },
onDismiss = { onDismiss = {
dismissedVersion = availableUpdate?.versionName
showUpdateDialog = false showUpdateDialog = false
} }
) )
@@ -0,0 +1,37 @@
package com.expapp.trigger.update
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.os.Build
import android.widget.Toast
class InstallStatusReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)
when (status) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
val confirmationIntent = 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)
}
if (confirmationIntent != null) {
confirmationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(confirmationIntent)
}
}
PackageInstaller.STATUS_SUCCESS -> {
Toast.makeText(context, "Update installed successfully!", Toast.LENGTH_SHORT).show()
}
else -> {
val message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)
if (!message.isNullOrBlank()) {
Toast.makeText(context, "Update: $message", Toast.LENGTH_SHORT).show()
}
}
}
}
}
@@ -1,7 +1,9 @@
package com.expapp.trigger.update package com.expapp.trigger.update
import android.app.PendingIntent
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.PackageInstaller
import android.net.Uri import android.net.Uri
import android.os.Build import android.os.Build
import android.os.Handler import android.os.Handler
@@ -45,7 +47,8 @@ class UpdateManager(
currentVersionName: String, currentVersionName: String,
callback: (UpdateCheckResult) -> Unit callback: (UpdateCheckResult) -> Unit
) { ) {
val url = "https://api.github.com/repos/$githubRepo/releases/latest" // Query releases list so we always inspect the highest semantic version
val url = "https://api.github.com/repos/$githubRepo/releases"
val request = Request.Builder() val request = Request.Builder()
.url(url) .url(url)
@@ -76,8 +79,25 @@ class UpdateManager(
val body = res.body?.string().orEmpty() val body = res.body?.string().orEmpty()
try { try {
val json = JsonParser.parseString(body).asJsonObject val jsonElement = JsonParser.parseString(body)
val releasesArray = if (jsonElement.isJsonArray) {
jsonElement.asJsonArray
} else {
// In case a single release object was returned
val arr = com.google.gson.JsonArray()
if (jsonElement.isJsonObject) arr.add(jsonElement.asJsonObject)
arr
}
var highestRelease: ReleaseInfo? = null
for (item in releasesArray) {
if (!item.isJsonObject) continue
val json = item.asJsonObject
if (json.has("draft") && json.get("draft").asBoolean) continue
val tagName = json.get("tag_name")?.asString.orEmpty() val tagName = json.get("tag_name")?.asString.orEmpty()
val cleanVer = tagName.removePrefix("v").removePrefix("V").trim()
val title = json.get("name")?.asString?.ifBlank { tagName } ?: tagName val title = json.get("name")?.asString?.ifBlank { tagName } ?: tagName
val changelog = json.get("body")?.asString.orEmpty() val changelog = json.get("body")?.asString.orEmpty()
@@ -99,26 +119,33 @@ class UpdateManager(
} }
} }
if (apkUrl.isNullOrBlank()) { 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( val releaseInfo = ReleaseInfo(
tagName = tagName, tagName = tagName,
versionName = cleanRemoteVersion, versionName = cleanVer,
title = title, title = title,
changelog = changelog, changelog = changelog,
downloadUrl = apkUrl, downloadUrl = apkUrl,
apkFileName = apkName, apkFileName = apkName,
sizeBytes = apkSize sizeBytes = apkSize
) )
if (highestRelease == null || isNewerVersion(cleanVer, highestRelease.versionName)) {
highestRelease = releaseInfo
}
}
}
if (highestRelease == null) {
runOnMain { callback(UpdateCheckResult.UpToDate) }
return
}
val cleanLocalVersion = currentVersionName.removePrefix("v").removePrefix("V").trim()
if (isNewerVersion(highestRelease.versionName, cleanLocalVersion)) {
runOnMain { runOnMain {
callback(UpdateCheckResult.UpdateAvailable(releaseInfo)) callback(UpdateCheckResult.UpdateAvailable(highestRelease))
} }
} else { } else {
runOnMain { callback(UpdateCheckResult.UpToDate) } runOnMain { callback(UpdateCheckResult.UpToDate) }
@@ -251,6 +278,48 @@ class UpdateManager(
} }
} }
try {
val packageInstaller = 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 sessionId = packageInstaller.createSession(params)
val session = packageInstaller.openSession(sessionId)
apkFile.inputStream().use { input ->
session.openWrite("package", 0, apkFile.length()).use { output ->
input.copyTo(output)
session.fsync(output)
}
}
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
val receiverIntent = Intent(context, InstallStatusReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
context,
sessionId,
receiverIntent,
flags
)
session.commit(pendingIntent.intentSender)
session.close()
} catch (e: Exception) {
// Fallback to FileProvider VIEW intent if session API is unsupported by vendor ROM
fallbackInstall(apkFile)
}
}
private fun fallbackInstall(apkFile: File) {
try {
val apkUri = FileProvider.getUriForFile( val apkUri = FileProvider.getUriForFile(
context, context,
"${context.packageName}.fileprovider", "${context.packageName}.fileprovider",
@@ -262,6 +331,7 @@ class UpdateManager(
flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK
} }
context.startActivity(installIntent) context.startActivity(installIntent)
} catch (_: Exception) {}
} }
companion object { companion object {