4 Commits
6 changed files with 205 additions and 80 deletions
+7 -2
View File
@@ -47,8 +47,13 @@ jobs:
elif [[ "${{ github.ref }}" == refs/tags/v* ]]; then
TAG="${GITHUB_REF#refs/tags/}"
else
# On pushes to main, generate a version based on run number
TAG="v1.0.${{ github.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 }}"
fi
fi
echo "TAG=$TAG" >> $GITHUB_OUTPUT
echo "Release tag will be $TAG"
+2 -2
View File
@@ -11,8 +11,8 @@ android {
applicationId = "com.expapp.trigger"
minSdk = 24
targetSdk = 34
versionCode = 1
versionName = "1.0"
versionCode = 3
versionName = "1.0.3"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
+4
View File
@@ -31,6 +31,10 @@
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<receiver
android:name=".update.InstallStatusReceiver"
android:exported="false" />
</application>
</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.SystemUpdate
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.Icon
import androidx.compose.material3.IconButton
@@ -110,6 +110,7 @@ fun MainScreen(
val updateManager = remember { UpdateManager(context) }
var availableUpdate by remember { mutableStateOf<ReleaseInfo?>(null) }
var showUpdateDialog by remember { mutableStateOf(false) }
var dismissedVersion by remember { mutableStateOf<String?>(null) }
var downloadState by remember { mutableStateOf<DownloadState>(DownloadState.Idle) }
var isCheckingUpdate by remember { mutableStateOf(false) }
@@ -120,7 +121,9 @@ fun MainScreen(
when (result) {
is UpdateCheckResult.UpdateAvailable -> {
availableUpdate = result.info
showUpdateDialog = true
if (showToast || dismissedVersion != result.info.versionName) {
showUpdateDialog = true
}
}
is UpdateCheckResult.UpToDate -> {
if (showToast) {
@@ -154,16 +157,12 @@ fun MainScreen(
fun syncEndpoints(showToast: Boolean = false) {
val current = repository.getDevices()
if (current.isEmpty()) {
checkAppUpdate(showToast)
return
}
if (current.isEmpty()) return
isSyncing = true
var updated = 0; var completed = 0
val total = current.count { it.r2Url.isNotBlank() }
if (total == 0) {
isSyncing = false
checkAppUpdate(showToast)
return
}
current.filter { it.r2Url.isNotBlank() }.forEach { device ->
@@ -180,7 +179,6 @@ fun MainScreen(
if (updated > 0) "Endpoints updated" else "Already up to date",
Toast.LENGTH_SHORT
).show()
checkAppUpdate(showToast)
}
}
}
@@ -241,33 +239,37 @@ fun MainScreen(
modifier = modifier.fillMaxSize(),
containerColor = BgBase,
topBar = {
CenterAlignedTopAppBar(
TopAppBar(
title = {
Row(verticalAlignment = Alignment.CenterVertically) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(start = 2.dp)
) {
Icon(
Icons.Default.Terminal,
contentDescription = null,
tint = GreenVibrant,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(10.dp))
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "DEVICE TRIGGER",
fontSize = 14.sp,
fontSize = 13.sp,
fontWeight = FontWeight.Bold,
letterSpacing = 2.sp,
letterSpacing = 1.5.sp,
color = TextPrimary,
fontFamily = FontFamily.Monospace
fontFamily = FontFamily.Monospace,
maxLines = 1
)
val onlineCount = devices.count { nodeStatuses[it.id]?.isOnline == true }
if (devices.isNotEmpty() && onlineCount > 0) {
Spacer(modifier = Modifier.width(10.dp))
Spacer(modifier = Modifier.width(8.dp))
Box(
modifier = Modifier
.clip(CircleShape)
.background(OnlineBg)
.border(1.dp, OnlineBorder, CircleShape)
.padding(horizontal = 8.dp, vertical = 2.dp)
.padding(horizontal = 7.dp, vertical = 2.dp)
) {
Text(
"$onlineCount online",
@@ -282,27 +284,31 @@ 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
IconButton(
onClick = { showUpdateDialog = true },
modifier = Modifier.size(40.dp)
) {
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
)
Box(contentAlignment = Alignment.TopEnd) {
Icon(
Icons.Default.SystemUpdate,
contentDescription = "Update available",
tint = GreenVibrant,
modifier = Modifier.size(20.dp)
)
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(
Icons.Default.Refresh,
"Sync",
@@ -311,12 +317,13 @@ fun MainScreen(
)
}
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)
}
},
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
colors = TopAppBarDefaults.topAppBarColors(
containerColor = BgSurface
)
)
@@ -429,9 +436,11 @@ fun MainScreen(
}
},
onInstall = { file ->
showUpdateDialog = false
updateManager.installApk(file)
},
onDismiss = {
dismissedVersion = availableUpdate?.versionName
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
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.net.Uri
import android.os.Build
import android.os.Handler
@@ -45,7 +47,8 @@ class UpdateManager(
currentVersionName: String,
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()
.url(url)
@@ -76,49 +79,73 @@ class UpdateManager(
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 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
}
val assets = json.getAsJsonArray("assets")
var apkUrl: String? = null
var apkName = "app-release.apk"
var apkSize = 0L
var highestRelease: ReleaseInfo? = null
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
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 cleanVer = tagName.removePrefix("v").removePrefix("V").trim()
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()) {
val releaseInfo = ReleaseInfo(
tagName = tagName,
versionName = cleanVer,
title = title,
changelog = changelog,
downloadUrl = apkUrl,
apkFileName = apkName,
sizeBytes = apkSize
)
if (highestRelease == null || isNewerVersion(cleanVer, highestRelease.versionName)) {
highestRelease = releaseInfo
}
}
}
if (apkUrl.isNullOrBlank()) {
if (highestRelease == null) {
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
)
if (isNewerVersion(highestRelease.versionName, cleanLocalVersion)) {
runOnMain {
callback(UpdateCheckResult.UpdateAvailable(releaseInfo))
callback(UpdateCheckResult.UpdateAvailable(highestRelease))
}
} else {
runOnMain { callback(UpdateCheckResult.UpToDate) }
@@ -251,17 +278,60 @@ class UpdateManager(
}
}
val apkUri = FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
apkFile
)
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 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
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)
}
context.startActivity(installIntent)
}
private fun fallbackInstall(apkFile: File) {
try {
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)
} catch (_: Exception) {}
}
companion object {